如何重新安排/操纵数据?

时间:2014-01-28 23:40:35

标签: r data-manipulation

我有一个实验室实验的数据集。数据现在采用以下形式:

ColumnID Soiltype Treatment Concentration1 Concentration2 Concentration3
1        Oh       Control   29             31             34
2        LOf      Treatment 100            99             94
3        Oh       Treatment 80             83             78

如何操作数据,使其如下所示:

ColumnID Soiltype Treatment Concentration
1        Oh       Control   29
1        Oh       Control   31
1        Oh       Control   34
2        LOf      Treatment 100
2        LOf      Treatment 99
2        LOf      Treatment 94
3        Oh       Treatment 80
3        Oh       Treatment 83
3        Oh       Treatment 78

我希望我已经清楚地说明了这个问题。任何google-fu都无济于事。任何提示或代码都受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

这属于将数据重塑为长形式的一般类别(对于您未来的google-fu参考):

library(reshape2)

melt(df, id.var = c('ColumnID', 'Soiltype', 'Treatment'),
         value.name = "Concentration")
#  ColumnID Soiltype Treatment       variable Concentration
#1        1       Oh   Control Concentration1            29
#2        2      LOf Treatment Concentration1           100
#3        3       Oh Treatment Concentration1            80
#4        1       Oh   Control Concentration2            31
#5        2      LOf Treatment Concentration2            99
#6        3       Oh Treatment Concentration2            83
#7        1       Oh   Control Concentration3            34
#8        2      LOf Treatment Concentration3            94
#9        3       Oh Treatment Concentration3            78

删除额外的列并订购留给读者。