2016-08-21 42 views
0

我有其被构造这样一个数据帧:长到宽与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 

从这个我想获得的数据帧与两条线,一条用于nam每个值和变量 var1_round1var1_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 

我能想到的最接近的将是一些有创意的方式来使用spread(),但我似乎无法弄清楚。

回答

4

我们可以使用tidyr/dplyr来做到这一点。我们gather数据集为'long'格式,unite'变量'和'round'创建'var',然后spread为'宽'格式。

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 

注: 'VAL' 是不同的OP没有设置seedrunif