Borrar filtros
Borrar filtros

How can I transpose a dataset or table?

444 visualizaciones (últimos 30 días)
MathWorks Support Team
MathWorks Support Team el 26 de Mzo. de 2018
Comentada: Peter Perkins el 14 de Mayo de 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?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 16 de Ag. de 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 comentarios
Peter Perkins
Peter Perkins el 19 de Abr. de 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 el 14 de Mayo de 2019
"Beginning in R2018a, the best way to to this is rows2vars, as that method deals with things like variable names."

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Tables en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by