如何将数据重新排列到每行一个记录中?

时间:2015-10-19 09:05:32

标签: r reshape2

我遇到了解如何使用R令人满意地重新排列数据的问题。我有数据:

id     animal    colour    value1    value2    value3   etc.
1      pig       blue      3.1       4.0       1.2            
1      pig       orange    3.05      4.1       NA                
1      pig       pink      3.05      3.9       1.25            
1      pig       mauve     2.95      4.0       NA                 
1      elephant  blue      15.03     4.03      11.0          
1      elephant  pink      15.13     4.0       14.95
2      pig       blue      4.1       ...

我希望获得类似的内容(列名称/顺序无关紧要):

id     pig_blue_value1  pig_blue_value2  pig_blue_value3  pig_orange_value1  pig_orange_value2 etc.
1      3.1              4.0              1.2              3.05               4.1
2      4.1              ...

我已经玩过reshape2的熔化和铸造,但到目前为止还没有达到任何令人满意的效果。感谢。

bluemoo <- data.frame(id=c(1,1,1,1,1,1,2),animal=c("pig","pig","pig","pig","elephant","elephant","pig"),colour=c("blue","orange","pink","mauve","blue","pink","blue"),value1=c(3.1,3.05,3.05,2.95,15.03,15.13,4.1),value2=c(4.0,4.1,3.9,4.0,4.03,4.0,NA),value3=c(1.2,NA,1.25,NA,11.0,14.95,NA))

1 个答案:

答案 0 :(得分:4)

使用CRAN上最新的data.table版本

尝试此操作
library(data.table) # v 1.9.6+
dcast(setDT(bluemoo), id ~ animal + colour, value.var = names(bluemoo)[-(1:3)])
#    id value1_elephant_blue value1_elephant_pink value1_pig_blue value1_pig_mauve value1_pig_orange value1_pig_pink value2_elephant_blue
# 1:  1                15.03                15.13             3.1             2.95              3.05            3.05                 4.03
# 2:  2                   NA                   NA             4.1               NA                NA              NA                   NA
#    value2_elephant_pink value2_pig_blue value2_pig_mauve value2_pig_orange value2_pig_pink value3_elephant_blue value3_elephant_pink
# 1:                    4               4                4               4.1             3.9                   11                14.95
# 2:                   NA              NA               NA                NA              NA                   NA                   NA
#    value3_pig_blue value3_pig_mauve value3_pig_orange value3_pig_pink
# 1:             1.2               NA                NA            1.25
# 2:              NA               NA                NA              NA