Effacer les filtres
Effacer les filtres

How can I transpose a dataset or table?

444 vues (au cours des 30 derniers jours)
MathWorks Support Team
MathWorks Support Team le 26 Mar 2018
Commenté : Peter Perkins le 14 Mai 2019
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?

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 16 Août 2018
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 commentaires
Peter Perkins
Peter Perkins le 19 Avr 2018
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 le 14 Mai 2019
"Beginning in R2018a, the best way to to this is rows2vars, as that method deals with things like variable names."

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by