フィルターのクリア

How can I transpose a dataset or table?

444 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2018 年 3 月 26 日
コメント済み: Peter Perkins 2019 年 5 月 14 日
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
MathWorks Support Team 2018 年 8 月 16 日
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 Center および File ExchangeTables についてさらに検索

タグ

タグが未入力です。

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by