'splitapply' syntax to index multiple columns in a timetable
8 次查看(过去 30 天)
显示 更早的评论
I would like to create a timetable using the split apply function applied to an existing timetable.
testTT = timetable(tmin, duration_min, splitapply(@mean, TT1.I, grp), ...
splitapply(@mean, TT1.KE, grp), ...
splitapply(@sum, TT1.num, grp), ...
splitapply(@mean, TT1.D, grp), ...
splitapply(@sum, TT1{10:1033}), grp));
You can see in the last splitapply command where I'm trying to apply the 'sum' function to 1024 total columns according to the group called 'grp'. I know my syntax is incorrect. But, I also don't know if what I'm trying here is possible (at least the way I'm doing it).
Is there a better approach?
2 个评论
dpb
2021-11-19
What is TT1{10:1033} intended to represent, again? The curlies will return an array, not a table which all the dot operations will, but it also lacks a 2D reference--it's only a 1D subscripting expression.
For the above to have any chance, the heights will all have to be the same.
Perhaps you're looking for
splitapply(@sum, TT1(:,10:1033)), grp)
on the last one?
Kelly Kearney
2021-11-20
Unfortunately that syntax isn't valid. You'd need to modify the call to sum to loop over multiple inputs:
% Small sample table
TT1 = array2table(rand(10,5), 'variablenames', {'one','two','three','four','five'});
grp = randi(2, 10, 1);
% One-liner with sum wrapper
testTT1 = array2table(...
splitapply(@(varargin) cellfun(@sum, varargin), TT1, grp), ...
'variableNames', TT1.Properties.VariableNames)
% Using loops
testTT2 = table;
vname = TT1.Properties.VariableNames;
for ii = 1:length(vname)
testTT2.(vname{ii}) = splitapply(@sum, TT1.(vname{ii}), grp);
end
testTT2
% The I-wish-it-worked-this-way syntax
testTTbad = splitapply(@sum, TT1, grp);
回答(1 个)
Kelly Kearney
2021-11-19
编辑:Kelly Kearney
2021-11-20
I really wish splitapply did allow you to pass a table as input and apply the same function to each column of that input. Unfortunately, it doesn't (it will accept table input, but then expects a function that treats each table column as a separate input variable). Instead, a loop is probably the easiest way to do this:
testTT = timetable(tmin, duration_min, splitapply(@mean, TT1.I, grp), ...
splitapply(@mean, TT1.KE, grp), ...
splitapply(@sum, TT1.num, grp), ...
splitapply(@mean, TT1.D, grp));
% Add the summed variables
vname = TT1.Properties.VariableNames(10:1033);
for ii = 1:length(vname)
testTT.(vname{ii}) = splitapply(@sum, TT1.(vname{ii}), grp);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Preprocessing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!