dplyr长到宽

The*_*dor 2 r reshape2 dplyr

我有一个数据框,结构如下:

dd <- data.frame(round = c("round1", "round2", "round1", "round2"),
                 var1 = c(22, 11, 22, 11),
                 var2 = c(33, 44, 33, 44),
                 nam = c("foo", "foo", "bar", "bar"),
                 val = runif(4))

   round var1 var2 nam        val
1 round1   22   33 foo 0.32995729
2 round2   11   44 foo 0.89215038
3 round1   22   33 bar 0.09213526
4 round2   11   44 bar 0.82644723
Run Code Online (Sandbox Code Playgroud)

从这个我想获得的数据帧与两条线,一个用于的每个值nam和变量 var1_round1,var1_round2,var2_round1,var2_round2,val_round1,val_round2.我真的想找到一个dplyr解决方案.

  nam var1_round1 var1_round2 var2_round1 var2_round2 val_round1 val_round2
1 foo          22          11          33          44 0.32995729  0.8921504
2 bar          22          11          33          44 0.09213526  0.8264472
Run Code Online (Sandbox Code Playgroud)

我能想到的最接近的事情就是以spread()一种创造性的方式使用,但我似乎无法弄明白.

akr*_*run 7

我们可以用它tidyr/dplyr来做到这一点.我们gather的数据集为'long'格式,unite'variable'和'round'用于创建'var'然后再spread为'wide'格式.

library(dplyr)
library(tidyr)
gather(dd, variable, value, var1, var2, val) %>%
         unite(var, variable, round) %>% 
         spread(var, value)
#  nam val_round1 val_round2 var1_round1 var1_round2 var2_round1 var2_round2
#1 bar  0.7187271  0.6022287          22          11          33          44
#2 foo  0.2672339  0.7199101          22          11          33          44
Run Code Online (Sandbox Code Playgroud)

注意:'val'是不同的,因为OP没有设置seedforrunif