필터 지우기
필터 지우기

How to include a wide table's VariableDescriptions as an additiolnal column when stacking the table?

조회 수: 1 (최근 30일)
I would like to make a wide table's VariableDescriptions as an additional column when I stack the table. I have written some codes to do it. They work (in a dirty manner). Is there a better way?
T = cell2table({'A', 2, 3, 3; 'B', 5, 5, 7}, "VariableNames", {'AB', 'x', 'y', 'z'});
% variable descriptions
T.Properties.VariableDescriptions = {'AB', 'xdes', 'ydes', 'zdes'};
S = stack(T, 2:4, "IndexVariableName",'xyz', 'NewDataVariableName','value')
S = 6×3 table
AB xyz value _____ ___ _____ {'A'} x 2 {'A'} y 3 {'A'} z 3 {'B'} x 5 {'B'} y 5 {'B'} z 7
% duplicate the table, using the variable descriptions as new variable names.
T2 = T;
T2.Properties.VariableNames = T.Properties.VariableDescriptions;
% stack the second table
S2 = stack(T2, 2:4, "IndexVariableName",'xyzdes', 'NewDataVariableName','value');
% add the descriptions as a new column to the first table
S.xyzdes = S2.xyzdes;
S = movevars(S, "xyzdes", "After", "xyz")
S = 6×4 table
AB xyz xyzdes value _____ ___ ______ _____ {'A'} x xdes 2 {'A'} y ydes 3 {'A'} z zdes 3 {'B'} x xdes 5 {'B'} y ydes 5 {'B'} z zdes 7

채택된 답변

Divyanshu
Divyanshu 2023년 4월 18일
The key concept used here is of a Map where variable names of the table are keys, and their values are the variable descriptions. For simplicity I have assumed names to be in names’ and descriptions in desc.
Here is a demo script of doing the same where a new column is added at the end of the stacked table:
names = ["x" "y" "z"];
desc = ["xD" "yD" "zD"];
M = containers.Map(names,desc);
col2 = S(:,2);
len = height(col2);
colN = []
for i=1:len
colN = [colN;string(M(string(col2{i,:})))];
end
colN = table(colN)
S = [S colN]
In the above script S is the stacked table that was created by your code.
The vector ‘colN is the new column vector which holds the descriptions.
Please refer to the following documentation to get more information about Maps:
  댓글 수: 1
Simon
Simon 2023년 4월 23일
편집: Simon 2023년 4월 23일
Thanks for the answer. I didn't know 'containers.Map' before. But Matlab has just created 'dictionary', which serves similar purpose and can take more flexible data type. Anyway, key-value mapping is a great idea in solving my problem.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by