How to find the total value by category in a table

14 ビュー (過去 30 日間)
julios
julios 2019 年 1 月 2 日
コメント済み: Cris LaPierre 2019 年 1 月 23 日
Ejemplo.JPG

採用された回答

Cris LaPierre
Cris LaPierre 2019 年 1 月 2 日
編集済み: Cris LaPierre 2019 年 1 月 2 日
G = findgroups(Table.Clase);
Result = splitapply(@sum,Table.Monto,G);
Result = table(categories(Table.Clase),Result,'VariableNames',{'Clase','Monto'})
  7 件のコメント
Cris LaPierre
Cris LaPierre 2019 年 1 月 4 日
Ah, you are in 2017a. It looks like reordercats did not yet support the string data type.
Update the line that uses string to use cellstr instead
[cats,ia,~] = unique(cellstr(Table.Clase));
julios
julios 2019 年 1 月 4 日
That's right !!!, the final result has a initial order. Thank you very much !!

サインインしてコメントする。

その他の回答 (2 件)

Peter Perkins
Peter Perkins 2019 年 1 月 23 日
The problem with Chris' solution is that by going through findgroups in that way, you lose all the categoricalness of your grouping variable. You can work around that in splitapply in a few ways, one of which Chris shows, but here's something more direct:
>> Clase = categorical({'w'; 'w'; 'w'; 'b'; 'b'; 'y'},{'w' 'b' 'y'});
>> Monto = [1;2;3;4;5;6];
>> t = table(Clase,Monto)
t =
6×2 table
Clase Monto
_____ _____
w 1
w 2
w 3
b 4
b 5
y 6
>> tsum = varfun(@mean,t,'GroupingVariable','Clase')
tsum =
3×3 table
Clase GroupCount mean_Monto
_____ __________ __________
w 3 2
b 2 4.5
y 1 6
>> categories(tsum.Clase)
ans =
3×1 cell array
{'w'}
{'b'}
{'y'}
In (very) recent versions of MATLAB, there's also groupsummary:
>> groupsummary(t,"Clase","mean")
ans =
3×3 table
Clase GroupCount mean_Monto
_____ __________ __________
w 3 2
b 2 4.5
y 1 6
varfun only works for tables, whereas groupsummary is more widel applicable.
  1 件のコメント
Cris LaPierre
Cris LaPierre 2019 年 1 月 23 日
Not sure what you mean by losing its categoricalness.
>> summary(Result)
Variables:
Clase: 3×1 categorical
Values:
White 1
Black 1
Yellow 1
Monto: 3×1 double
Values:
Min 4
Median 5
Max 6

サインインしてコメントする。


Image Analyst
Image Analyst 2019 年 1 月 2 日
You can use grpstats() to get the stats by group, if you have the Statistics and Machine Learning Toolbox. It doesn't have sum but it has count and mean so you can multiply those to get the sum. Attach your table in a .mat file, and your expected results if you need more guidance.
  3 件のコメント
Image Analyst
Image Analyst 2019 年 1 月 3 日
OK, no problem. You accepted it so it looks like it's solved your problem. Or maybe not?
julios
julios 2019 年 1 月 4 日
Tank you for your interest, and Yes the principal problem has been solved, we only tuning a response.

サインインしてコメントする。

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by