How to sum over grouped data in a table
Afficher commentaires plus anciens
Suppose I have a table like this toy example:
>> groups = { 'a'; 'a'; 'b'; 'b'; 'c'; 'c'};
>> values = [1;2;3;4;5;6];
>> exampletable = table(groups, values);
I want another column in the table that finds the sum of the values for each group. How can I do this?
Réponse acceptée
Plus de réponses (1)
Peter Perkins
le 11 Mar 2019
It seems more likely that you would want the sum for each group in a table with one row for each group. There are several simple ways to do that, including findgroups/splitapply, groupsummary, and this version using varfun:
>> groups = { 'a'; 'a'; 'b'; 'b'; 'c'; 'c'};
>> values = [1;2;3;4;5;6];
>> exampletable = table(groups, values);
>> exampletable.groups = categorical(exampletable.groups) % convert to categorical IN the table
>> sums = varfun(@sum,exampletable,'GroupingVariable','groups')
sums =
3×3 table
groups GroupCount sum_values
______ __________ __________
a 2 3
b 2 7
c 2 11
If broadcasting the summed values out to each row of the original table is the goal, findgroups does the trick.
>> igroup = findgroups(exampletable.groups)
>> exampletable.sums = sums.sum_values(igroup)
All of this is in base MATLAB.
Catégories
En savoir plus sur Repeated Measures and MANOVA dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!