Can you have a multilevel table?
73 次查看(过去 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!