Calculating Contribution by group
Show older comments
Hi,
I am trying to calculate the contribution within a group. Currnetly I am using below procedure, looking for ways to do it faster/ shorter format
tdata= table([2220;2220;2220;2768;3032;3032;3797;3797;3797;3797],["UNITED KINGDOM";"UNITED KINGDOM";"UNITED KINGDOM";"UNITED KINGDOM";"GERMANY";"UNITED KINGDOM";"UNITED KINGDOM";"UNITED KINGDOM";"UNITED KINGDOM";"UNITED KINGDOM"],["GBR_SW";"GBR_B";"GBR_B";"GBR_WC";"DEU_60";"GBR_SW";"GBR_WC";"GBR_GU";"GBR_NW";"GBR_WC"],[76449.0759200000;12117334.4450944;12197494.6611334;0;29611.6627483313;6501105.79043613;27555.3049246048;65116.2649056192;65568.0789443064;126369.558005001],'VariableNames',{'EB','Country','CRESTACode','Limit'})
% Aggregating by group of EB-Country-Cresta
[ uniqEBCntry_2Cresta, ~, JGrp] = unique( tdata( :, {'EB','Country','CRESTACode'}));
uniqEBCntry_2Cresta.count = accumarray( JGrp, 1, [], @sum);
uniqEBCntry_2Cresta.Limit = accumarray( JGrp, tdata.Limit, [], @sum);
% Summing across all cresta
[ uniqEBCntry, ~, JGrp] = unique( uniqEBCntry_2Cresta( :, {'EB','Country'}));
uniqEBCntry.Limit_byEBCntry = accumarray( JGrp, uniqEBCntry_2Cresta.Limit, [], @sum);
%Contribution by CRESTA for each EB-Country
uniqEBCntry_2Cresta = innerjoin( uniqEBCntry_2Cresta, uniqEBCntry, 'Keys',{'EB','Country'},'RightVariables',{'Limit_byEBCntry'});
uniqEBCntry_2Cresta.contrib = uniqEBCntry_2Cresta.Limit./ uniqEBCntry_2Cresta.Limit_byEBCntry;
Thanks
2 Comments
Pete sherer
on 20 Jun 2021
Scott MacKenzie
on 29 Jul 2021
It's nice that you have posted code, but, in this case, it might also help if you clearly define "contribution within a group" and give an example with the data in your table.
Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!