How to create a pivot table from this table (revised)

2 visualizaciones (últimos 30 días)
alpedhuez
alpedhuez el 15 de Ag. de 2021
Comentada: alpedhuez el 15 de Ag. de 2021
Suppose I have a table T
location gender
-----------------------------------------------------------
Customer 1 NY male
Customer 2 LA female
Customer 3 Austin female
Customer 4 LA female
Then I want to create a pivot table
Male Female
--------------------------------------------
NY 1 0
LA 0 2
Austin 0 1
I checked unstack and grpstat but I am not sure. What will be a next step?

Respuesta aceptada

Dave B
Dave B el 15 de Ag. de 2021
Editada: Dave B el 15 de Ag. de 2021
Maybe there's a simpler path, but how about using groupsummary followed by unstack?
% Generate your table
cust = {'Customer 1' 'Customer 2' 'Customer 3'};
location = categorical({'NY' 'LA' 'Austin'},{'NY' 'LA' 'Austin'})';
gender = categorical({'male' 'female' 'female'},{'male' 'female'})';
t=table(location,gender);
% groupsumamry for counts, unstack for pivot, and then set NaNs to 0
s=groupsummary(t,{'location' 'gender'});
result=unstack(s,'GroupCount','gender');
result.female(isnan(result.female))=0;
result.male(isnan(result.male))=0;
disp(result)
location male female ________ ____ ______ NY 1 0 LA 0 1 Austin 0 1

Más respuestas (1)

the cyclist
the cyclist el 15 de Ag. de 2021
What you want to do is not really a pivot:
% Create your table
customer = {'1';'2';'3'};
location = {'NY';'LA';'Austin'};
gender = {'male';'female';'female'};
tbl = table(customer,location,gender)
tbl = 3×3 table
customer location gender ________ __________ __________ {'1'} {'NY' } {'male' } {'2'} {'LA' } {'female'} {'3'} {'Austin'} {'female'}
% You don't need the above. It is just to create your data.
% Create columns for male and female
tbl.male = double(strcmp(tbl.gender,'male'));
tbl.female = double(strcmp(tbl.gender,'female'));
% Drop the gender column
tbl.gender = []
tbl = 3×4 table
customer location male female ________ __________ ____ ______ {'1'} {'NY' } 1 0 {'2'} {'LA' } 0 1 {'3'} {'Austin'} 0 1
  3 comentarios
the cyclist
the cyclist el 15 de Ag. de 2021
Ah. I thought you just wanted to replace male/female with binary variables.
alpedhuez
alpedhuez el 15 de Ag. de 2021
Yes I should have provided more general examples. Thank you.

Iniciar sesión para comentar.

Categorías

Más información sobre Tables en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by