R:在没有for循环的情况下将"短格式"数据转换为"长格式"数据?

Max*_*y-B 4 r dataframe

假设我有一个像这样的R数据帧:

  Subject Session  Property.A Property.B Property.C
1     100       1 -1.22527548 -0.9193751 -1.7501693
2     100      10  2.30627980  1.8940830 -0.8443976
3     100       2  2.33243332 -0.5860868 -4.2074489
4     100       3  0.38130810 -0.7336206  4.8016230
5     100       4  1.44685875  0.5066249  2.0138624
6     100       5  0.08907721 -0.3715202  1.4983700
Run Code Online (Sandbox Code Playgroud)

我听说过这种称为"短格式"或"宽格式"的数据框架.现在假设我想让它看起来像这样,我听说它叫做"长形式":

  Subject Session  Property    Value
1     100       1         A   -1.2252754
2     100       1         B   -0.9193751
3     100       1         C   -1.7501693
4     100       2         A    2.3324333
5     100       2         B   -0.5860868
6     100       2         C   -4.2074489
Run Code Online (Sandbox Code Playgroud)

也就是说,我有N列,我想减少到只有两个"名称/值"列,数据框中的任何其他列根据需要扩展重复值.

显然我可以用一堆for循环执行这个转换,但这看起来真的很难看,如果/当我添加更多属性列时,维护是很痛苦的.

有没有办法在R中用几行代码做到这一点?我还没有发现一些神奇的功能组合?

Cha*_*ase 11

使用melt包中的功能reshape2:

library(reshape2)
dat.m <- melt(dat, id.vars = c("Subject", "Session"))
Run Code Online (Sandbox Code Playgroud)

如果需要清理变量列的列名和/或值:

#change "variable" to "Property"
names(dat.m)[3] <- "Property"
#Drop "Property." from the column values
dat.m$Property <- gsub("Property\\.", "", dat.m$Property)
Run Code Online (Sandbox Code Playgroud)

  • 或者使用`reshape2`,它可以快得多 (3认同)