Using unstack in order to replicate Pivot Table created in Excel

1 view (last 30 days)
Hi,
my question is based on the following table:
var1 = {'sec1';'sec2';'sec3';'sec4';'sec5';'sec6';'sec7';'sec8'};
var2 = {'EQ';'EQ';'EQ';'EQ';'FI';'FI';'FI';'FI'};
var3 = {'EQ';'EQ';'CA';'FINALT';'FI';'FI';'CA';'FINALT'};
var4 = {'X1';'X2';'X3';'X4';'X5';'X6';'X7';'X4'};
var5 = [0.50;0.10;0.02;0.10;0.13;0.05;0.05;0.05];
T = table(var1,var2,var3,var4,var5);
Now I would like to replicate the Pivot table that is in the attached xlsx file and that looks like follows
image.JPG
Basically, I am trying to show the values for var5, the columns are grouped by var3 and subgrouped by var4. The rows are aggregated using group sums for var2.
I am trying to use the unstack function as follows:
unstack(T,{'var3','var4'},'var5','GroupingVariables', 'var2','AggregationFunction', @sum)
but I get the following error message:
Error using sum
Invalid data type. First argument must be numeric or logical.
I have tried other combinations, but not being able to replicate the Excel version.
  2 Comments
Mohammad Sami
Mohammad Sami on 24 Jan 2020
The first parameter is the value variable. Since you are using sum, this must be numeric. Your var3 and var4 are non-numeric. I suppose you meant var5. Your var3 and var4 would be the identity variable. Matlab only allows one. So probaly you need to merge var3 and var4.
unstack(T,'var5','var3','GroupingVariables', 'var2','AggregationFunction', @sum)
SpeedyGonzales
SpeedyGonzales on 24 Jan 2020
Thank you Mohammad. Merging var3 and var4 created another error. I think that based on your answer and additional playing around on my side it looks like I can't achieve what I want to do.

Sign in to comment.

Answers (0)

Categories

Find more on Tables 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!