R传播所有列

时间:2016-06-15 09:59:19

标签: r dplyr tidyr spread

我目前要做的是将所有列分散到多个列上,例如此数据框

Person_ID  Car_ID Car_Type Car_Speed
a          1      x        50
a          2      y        70
a          3      z        100
b          4      y        70

我想把它变成这个

Person_ID  Car_ID1 Car_Type1 Car_Speed1 Car_ID2 Car_Type2 Car_Speed2 Car_ID3 Car_Type3 Car_Speed3
a          1        x        50         2      y        70           3       z         100    
b          4        y        70

有人可以帮忙吗?谢谢。

1 个答案:

答案 0 :(得分:2)

使用来自dcast的{​​{1}}可以轻松完成此操作,这可能需要多个data.table

value.var

或创建按' Person_ID'

分组的序列列后,library(data.table)#v1.9.7+ dcast(setDT(df1), Person_ID~rowid(Person_ID), value.var = c("Car_ID", "Car_Type", "Car_Speed")) # Person_ID Car_ID_1 Car_ID_2 Car_ID_3 Car_Type_1 Car_Type_2 Car_Type_3 Car_Speed_1 Car_Speed_2 #1: a 1 2 3 x y z 50 70 #2: b 4 NA NA y NA NA 70 NA # Car_Speed_3 #1: 100 #2: NA 来自reshape
base R