Can you have a multilevel table?
조회 수: 78 (최근 30일)
이전 댓글 표시
I have a large table that has several groups of similar variables. I'd like to create levels of variables so I can group and access them easily- perhaps I need a struct or perhaps I am being lazy.
load patients
T1 = table(LastName,Gender,Age,Height,Weight,Systolic,Diastolic);
head(T1,3)
I can merge variables, but I seem to lose the nested variable names.
T2 = mergevars(T1,{'Systolic','Diastolic'},'NewVariableName','BloodPressure');
head(T2,3)
I'd like to be able to access the Systolic and Diastolic variable under BloodPressure like this:
T2.BloodPressure.Systolic
%but not this
T2.BloodPressure(:,1)
It's a lot harder for me to keep track of the index, and I am hoping I would be able to use Tab Completion.
Also, in the event there is more than one 'Blood Pressure', say I have BloodPressure1 and BloodPressure2 both with sub variables Systolic and DIastolic, I'd like to be able to get all the Systolics at once- something like
T2.{:}.Systolic
Hope that explains what I'm after, and hoping there's a way to get there. Thanks.
댓글 수: 0
채택된 답변
Voss
2022년 5월 25일
You can use 'MergeAsTable',true in mergevars:
load patients
T1 = table(LastName,Gender,Age,Height,Weight,Systolic,Diastolic);
head(T1,3)
T2 = mergevars(T1,{'Systolic','Diastolic'}, ...
'NewVariableName','BloodPressure', ...
'MergeAsTable',true);
head(T2,3)
T2.BloodPressure
T2.BloodPressure.Systolic
댓글 수: 4
Seth Furman
2022년 5월 31일
Starting in R2022a you can use patterns to index into tables (as well as in a number of table methods that accept table variable indices).
load patients
T1 = table(LastName,Gender,Age,Height,Weight,Systolic,Diastolic);
T2 = head(mergevars(T1,{'Systolic','Diastolic'}, ...
'NewVariableName','BloodPressure', ...
'MergeAsTable',true),3);
T3 = renamevars(T2,{'Height','Weight'},{'Systolic','Diastolic'});
T3 = mergevars(T3,{'Systolic','Diastolic'}, ...
'NewVariableName','BloodPressure2', ...
'MergeAsTable',true)
bp = T3(:, "BloodPressure"+wildcardPattern)
bpSystolic = varfun(@(t) t(:, "Systolic"), bp)
bpSystolic.Properties.VariableNames = bp.Properties.VariableNames
추가 답변 (1개)
Adam Danz
2023년 1월 16일
편집: Adam Danz
2023년 1월 16일
An alternative to @Voss's execellent answer is to create the nested table(s) and then add the nested table(s) as a table variable to the main table (MATLAB R2018b or later).
load patients
BloodPressure = table(Systolic,Diastolic);
T1 = table(LastName,Gender,Age,Height,Weight, BloodPressure)
댓글 수: 3
Adam Danz
2023년 2월 6일
> I really like nested tables, but how can I run groupsummary on them?
Demo:
t3 = table(randi(2,5,1),rand(5,1),'VariableNames',{'a','b'});
t2 = table(rand(5,1),rand(5,1),t3,t3,'VariableNames',{'c','d','t3','t4'})
t1 = splitvars(t2)
groupsummary(t1,'t3_a', 'mean', 't3_b')
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!