Count frequency data from table

10 views (last 30 days)
DavidL88
DavidL88 on 25 Jun 2021
Commented: DavidL88 on 14 Jul 2021
I have a table T with two columns. I want to create two frequency tables from them for two groups - MLD and MOD. For these tables the rows would be 11, 12, 21, and 22. The columns would be P1, N12, P2, P3 and LPP. The frequnecy count would be filled in from the table below. is there a way to do this?
T =
MLD_HGH_CG_HGH_11_POR P3
MLD_HGH_CG_HGH_12_POL P1
MLD_HGH_CG_HGH_21_FCR P3
MLD_HGH_CG_HGH_22_CPL P1
MLD_HGH_CG_HGH_22_CPL P2
MOD_CG_11_CPR N1
MOD_CG_11_FCR N1
MOD_CG_12_CPL P2
MOD_CG_12_CPL P3
MOD_CG_12_CPL LPP
MOD_CG_12_CPR P3
Example of outcome for first 'MLD' table
P1 N1 P2 P3 LPP
11 0 0 0 1 0
12 1 0 0 0 0
21 0 0 0 1 0
22 1 0 1 0 0

Accepted Answer

Seth Furman
Seth Furman on 14 Jul 2021
This can be accomplished using groupsummary and unstack.
c = [ ...
"MLD_HGH_CG_HGH_11_POR" "P3"
"MLD_HGH_CG_HGH_12_POL" "P1"
"MLD_HGH_CG_HGH_21_FCR" "P3"
"MLD_HGH_CG_HGH_22_CPL" "P1"
"MLD_HGH_CG_HGH_22_CPL" "P2"
"MOD_CG_11_CPR" "N1"
"MOD_CG_11_FCR" "N1"
"MOD_CG_12_CPL" "P2"
"MOD_CG_12_CPL" "P3"
"MOD_CG_12_CPL" "LPP"
"MOD_CG_12_CPR" "P3"
];
t = table(c(:,1),c(:,2))
t = 11×2 table
Var1 Var2 _______________________ _____ "MLD_HGH_CG_HGH_11_POR" "P3" "MLD_HGH_CG_HGH_12_POL" "P1" "MLD_HGH_CG_HGH_21_FCR" "P3" "MLD_HGH_CG_HGH_22_CPL" "P1" "MLD_HGH_CG_HGH_22_CPL" "P2" "MOD_CG_11_CPR" "N1" "MOD_CG_11_FCR" "N1" "MOD_CG_12_CPL" "P2" "MOD_CG_12_CPL" "P3" "MOD_CG_12_CPL" "LPP" "MOD_CG_12_CPR" "P3"
t.Group = extract(t.Var1,digitsPattern)
t = 11×3 table
Var1 Var2 Group _______________________ _____ _____ "MLD_HGH_CG_HGH_11_POR" "P3" "11" "MLD_HGH_CG_HGH_12_POL" "P1" "12" "MLD_HGH_CG_HGH_21_FCR" "P3" "21" "MLD_HGH_CG_HGH_22_CPL" "P1" "22" "MLD_HGH_CG_HGH_22_CPL" "P2" "22" "MOD_CG_11_CPR" "N1" "11" "MOD_CG_11_FCR" "N1" "11" "MOD_CG_12_CPL" "P2" "12" "MOD_CG_12_CPL" "P3" "12" "MOD_CG_12_CPL" "LPP" "12" "MOD_CG_12_CPR" "P3" "12"
gs = groupsummary(t,["Group","Var2"],'IncludeEmptyGroups',true)
gs = 20×3 table
Group Var2 GroupCount _____ _____ __________ "11" "LPP" 0 "11" "N1" 2 "11" "P1" 0 "11" "P2" 0 "11" "P3" 1 "12" "LPP" 1 "12" "N1" 0 "12" "P1" 1 "12" "P2" 1 "12" "P3" 2 "21" "LPP" 0 "21" "N1" 0 "21" "P1" 0 "21" "P2" 0 "21" "P3" 1 "22" "LPP" 0
gs = unstack(gs,"GroupCount","Var2")
gs = 4×6 table
Group LPP N1 P1 P2 P3 _____ ___ __ __ __ __ "11" 0 2 0 0 1 "12" 1 0 1 1 2 "21" 0 0 0 0 1 "22" 0 0 1 1 0

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by