Averaging columns in table using only rows where a condition is met.
4 views (last 30 days)
Show older comments
Joshua Himmelstein
on 21 Apr 2022
Commented: Campion Loong
on 18 May 2022
I would like to find the mean (average) for values in columns 3, 4, 5, 6 using only rows where OOBS.night == 1. This average will be different than the entire column average, as I only want to include a subset of the column values.
I am open to suggestions - perhaps I am going about this wrong!
Thank you.
OOBS = table([hobo_times.OOBS23],[hobo_times.water_elevation_m_NAVD88],[tu_values_23'],[tu_values_27'],[tu_values_29'],[tu_values_35']);
OOBS.Properties.VariableNames = {'times','WtrLvlm','OOBS23','OOBS27','OOBS29','OOBS35'};
OOBS.night = (hour(OOBS.times)>=20 | hour(OOBS.times)<=6);
find(OOBS.night ==1 & OOBS.WtrLvlm>=0.33);
1 Comment
Campion Loong
on 18 May 2022
This is really just 1-line of code using groupsummary. The first few lines are just making up fake data, since there is no example data attached:
% Make up some data
Times = (datetime(2021,10,1):minutes(10):datetime(2021,10,31))';
WtrLvlm = rand(length(Times),1);
OOBS23 = rand(length(Times),1);
OOBS27 = rand(length(Times),1);
OOBS29 = rand(length(Times),1);
OOBS35 = rand(length(Times),1);
night = timeofday(Times) > hours(18); % assume 'night' means later than 6PM
tt = timetable(Times, WtrLvlm, OOBS23, OOBS27, OOBS29, OOBS35, night)
% This 1-liner is what you are actually after
NightAvg = groupsummary(tt,'night','mean')
% Now it's a slightly different 1-liner if you want to group
% by both 'night' and a 'WtrLvlm' threshold
% (like in your code example, but unlike your descriptions)
groupsummary(tt,["night" "WtrLvlm"],{'none', [0 0.33 Inf]}, "mean")
Accepted Answer
David Hill
on 21 Apr 2022
n_idx=hour(hobo_times.OOBS23)>=20 | hour(hobo_times.OOBS23)<=6;
m=mean([tu_values_23'(n_idx);tu_values_27'(n_idx);tu_values_29'(n_idx);tu_values_35'(n_idx)]);
More Answers (0)
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!