Weighted mean by groups

16 ビュー (過去 30 日間)
Maximilian  Schwarz
Maximilian Schwarz 2022 年 9 月 28 日
編集済み: dpb 2022 年 9 月 28 日
I am trying to get the weighted mean of values by group id but I don't undersnatnd why my ouput (Mean) is a matrix and not a vector.
id = { 'a'; 'a'; 'b'; 'b'; 'c'; 'c'};
values = [1;2;3;4;5;6];
weights = [0.5;0.7;0.3;0.4;0.5;0.1];
exampletable = table(id, weights, values);
G = findgroups(exampletable.id);
wmean = @(w,v)w'.*mean(v);
Mean = splitapply(wmean, exampletable.weights, exampletable.values, G)
id = { 'a'; 'a'; 'b'; 'b'; 'c'; 'c'};
values = [1;2;3;4;5;6];
weights = [0.5;0.7;0.3;0.4;0.5;0.1];
exampletable = table(id, weights, values);
G = findgroups(exampletable.id);
wmean = @(w,v)w'.*mean(v);
Mean = splitapply(wmean, exampletable.weights, exampletable.values, G)

採用された回答

dpb
dpb 2022 年 9 月 28 日
編集済み: dpb 2022 年 9 月 28 日
It's the wmean function definition that's doing it -- what you intended was
wmean = @(w,v)mean(w.*v);
trying that,
id = { 'a'; 'a'; 'b'; 'b'; 'c'; 'c'};
values = [1;2;3;4;5;6];
weights = [0.5;0.7;0.3;0.4;0.5;0.1];
exampletable = table(id, weights, values);
G = findgroups(exampletable.id);
Mean = splitapply(wmean, exampletable.weights, exampletable.values, G)
Mean = 3×1
0.9500 1.2500 1.5500
ADDENDUM
OBTW, you can do things like this without the explicit step of findgroups with groupsummary (or several other ways, as well)--
gmeans=groupsummary(exampletable,'id',wmean,{"weights","values"})
gmeans = 3×3 table
id GroupCount fun1_weights_values _____ __________ ___________________ {'a'} 2 0.95 {'b'} 2 1.25 {'c'} 2 1.55
  1 件のコメント
Maximilian  Schwarz
Maximilian Schwarz 2022 年 9 月 28 日
Thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by