传播到多个列

时间:2017-05-01 04:58:30

标签: r

我有一个data.frame,我希望传播类似dplyr的扩散函数,但有多个变量。

Code    Product 2008    2008_Unit   2015    2015_Unit   Type
010110  Pure-bred breeding horses and asses 1   Tons    NA  NA  Exports_Peru_US
010110  Pure-bred breeding horses and asses 6   Tons    NA  NA  Exports_Peru_World
010110  Pure-bred breeding horses and asses 55  Units   NA  NA  Exports_US_Peru
010110  Pure-bred breeding horses and asses 3899    Units   NA  NA  Exports_US_World
010110  Pure-bred breeding horses and asses 0   No quantity 6   Tons    Exports_World
010110  Pure-bred breeding horses and asses 31  Tons    NA  NA  Imports_Peru_US

我想把它变成:

Code    Product 2008_Exports_Peru_US    2008_Unit_Exports_Peru_US   2015_Exports_Peru_US    2015_Unit_Exports_Peru_US   2008_Exports_Peru_World ...
010110  Pure-bred breeding horses and asses 1   Tons    NA  NA  6   ...

因此每个代码只出现在一行中。

注意:并非所有代码都包含所有类型。

reshape2 + data.table有效

dcast(setDT(master), Code + Product ~ Type, value.var = c("2008","2008_Unit", "2015", "2015_Unit"))

1 个答案:

答案 0 :(得分:0)

reshape2 + data.table有效

master <- the data frame
dcast(setDT(master), Code + Product ~ Type, value.var = c("2008","2008_Unit", "2015", "2015_Unit"))