Average column data with specific values

2 ビュー (過去 30 日間)
Nick Austinos
Nick Austinos 2022 年 8 月 23 日
コメント済み: Nick Austinos 2022 年 8 月 23 日
I have the data below, I am trying to average the column gdppc for each country.

採用された回答

Robert U
Robert U 2022 年 8 月 23 日
Hi Faustine Enos,
I do not know how your data is available and what data type you chose. It is preferrable to use table type data. Then, you can adjust the following code snippet:
col_1 = {'Country A';'Country A';'Country A';'Country A';'Country B';'Country B';'Country B';'Country C'};
col_2 = [1; 2; 3; 4; 5; 6; 7; 8];
data = table(col_1,col_2,'VariableNames',{'Country','value'});
cCountry = unique(data.Country);
for ik = 1:numel(cCountry)
sumVal(ik) = sum(data.value(ismember(data.Country,cCountry{ik})));
disp(sprintf('%s %d',cCountry{ik},sumVal(ik)));
end
Country A 10 Country B 18 Country C 8
Kind regards,
Robert
  1 件のコメント
Nick Austinos
Nick Austinos 2022 年 8 月 23 日
Thanks it works now.

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

その他の回答 (1 件)

Simon Chan
Simon Chan 2022 年 8 月 23 日
Use function writetable to convert your data on a table array.
Then use function groupsummary as follows
G = groupsummary(T,"country","mean","gdppc") % where T is the table array
  1 件のコメント
Nick Austinos
Nick Austinos 2022 年 8 月 23 日
Hi it works really well.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by