How can I transpose a dataset or table?

444 次查看(过去 30 天)
How can I transpose a dataset or table (make the rows and columns switch) in MATLAB R2013b?
For example, I have the following dataset:
>> X = dataset({[1;2], 'a'}, {[100;200], 'b'}, 'ObsNames', {'c','d'})
X =
a b
c 1 100
d 2 200
and I would like to transpose the dataset:
>> Xt = X'
Xt =
c d
a 1 2
b 100 200
Similarly, if I have the same data stored in a table:
>> X = array2table([1 100; 2 200],'VariableNames',{'a','b'},'RowNames',{'c','d'})
X =
*a* *b*
_ ___
*c* 1 100
*d* 2 200
and I would like to transpose the table:
>> Xt = X'
Xt =
*c* *d*
___ ___
*a* 1 2
*b* 100 200
How can I do this?

采纳的回答

MathWorks Support Team
The ability to transpose a dataset or table using the transpose operator (') is not available in MATLAB R2013b, however this is possible using a combination of other commands.
For datasets, you can use a combination of 'dataset2cell' and 'cell2dataset' to convert the dataset into a cell array, transpose the cell array, then translate back into a dataset:
>> Xc = dataset2cell(X)
Xc =
'ObsNames' 'a' 'b'
'c' [1] [100]
'd' [2] [200]
>> Xt = cell2dataset(Xc','ReadObsNames',true)
Xt =
c d
a 1 2
b 100 200
For tables, you can use a combination of 'table2cell' and 'cell2table':
>> Xc = table2cell(X)
Xc =
[1] [100]
[2] [200]
>> Xt = cell2table(Xc','RowNames',X.Properties.VariableNames,'VariableNames',X.Properties.RowNames)
Xt =
c d
___ ___
a 1 2
b 100 200
As of MATLAB R2018a, you can also use the ROW2VARS function:
<https://www.mathworks.com/help/matlab/ref/rows2vars.html>
  2 个评论
Peter Perkins
Peter Perkins 2018-4-19
Converting to a cell array and back is probably not a good idea unless the table is fairly small. If the goal is to transpose the data in the table, it's a safe bet that all the data are the same type. Use table2array and array2table instead.
Beginning in R2018a, the best way to to this is rows2vars, as that method deals with things like variable names.
dataset is a class is the Statistics & Machine Learning Toolbox. If possible, it's a good idea to use tables instead.
Peter Perkins
Peter Perkins 2019-5-14
"Beginning in R2018a, the best way to to this is rows2vars, as that method deals with things like variable names."

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

尚未输入任何标签。

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by