Transform data from long to wide format

13 次查看(过去 30 天)
Hi community,
My data is currently in long format (data_long.csv) and I am trying to convert it to wide format (data_wide.csv).
I have 15 participants and 16 variables to do this for. Any tips would be great!
Thank you,
Danielle

回答(1 个)

Star Strider
Star Strider 2022-7-12
Use unstack, preferably the same unstack call with the same MATLAB version that produced the ‘data_wide’ file.
Experiment with it, since I cannot get the same result.
L1 = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1062580/data_long.csv')
L1 = 6×5 table
P Demo Time Con Var1 _ ____ ____ ___ _______ 1 1 1 1 0.11974 1 1 1 2 0.58441 1 1 2 1 0.79951 1 1 2 2 0.23271 1 1 3 1 0.53867 1 1 3 2 0.03069
W1 = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1062585/data_wide.csv')
W1 = 1×8 table
P Demo Var1_Time1_Con1 Var1_Time1_Con2 Var1_Time2_Con1 Var1_Time2_Con2 Var1_Time3_Con1 Var1_Time3_Con2 _ ____ _______________ _______________ _______________ _______________ _______________ _______________ 1 1 0.11974 0.58441 0.79951 0.23271 0.53867 0.03069
L1toW2 = unstack(L1,{'Var1','Time'},'Con')
Warning: Table variable names that were not valid MATLAB identifiers have been modified. Since table variable names must be unique, any table variable names that happened to match the new identifiers also have been modified.
To use the original INDVAR values as table variable names, set 'VariableNamingRule' to 'preserve'.
L1toW2 = 1×6 table
P Demo Var1_x1 Var1_x2 Time_x1 Time_x2 _ ____ _______ _______ _______ _______ 1 1 1.4579 0.84781 6 6
.
  2 个评论
Danielle Vickery-Howe
Hi Star Strider, thank you for your response!
I think I need to be able to unstack my data twice?
I can unstack one grouping variable, but I can't manage to unstack for the second.
I think the only way is going to be able to unstack Con by 'x1' 'x2' 'x3'. But I have not yet figured how to do this.
L1 = readtable("data_long.csv");
W1 = readtable("data_wide.csv");
TimeWide = unstack(L1,'Var1','Time')
Warning: Table variable names that were not valid MATLAB
identifiers have been modified. Since table variable names
must be unique, any table variable names that happened to
match the new identifiers also have been modified.
To use the original INDVAR values as table variable names, set
'VariableNamingRule' to 'preserve'.
TimeWide =
2×6 table
P Demo Con x1 x2 x3
_ ____ ___ _______ _______ _______
1 1 1 0.11974 0.79951 0.53867
1 1 2 0.58441 0.23271 0.03069
Star Strider
Star Strider 2022-7-13
It depends on wthe result you want. I used two grouping variables and it seemed to work (R2022a). The result provided seems to have changed over the last few versions. You will likely have to experiment with it.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by