我怎样才能把多重variables的重复测量扩散到广泛的格式?

我试图采取长格式的列,并将其传播到如下所示的宽格式。 我想用tidyr解决这个我正在投资的数据处理工具,但为了使这个答案更普遍,请提供其他解决scheme。

这是我有:

library(dplyr); library(tidyr) set.seed(10) dat <- data_frame( Person = rep(c("greg", "sally", "sue"), each=2), Time = rep(c("Pre", "Post"), 3), Score1 = round(rnorm(6, mean = 80, sd=4), 0), Score2 = round(jitter(Score1, 15), 0), Score3 = 5 + (Score1 + Score2)/2 ) ## Person Time Score1 Score2 Score3 ## 1 greg Pre 80 78 84.0 ## 2 greg Post 79 80 84.5 ## 3 sally Pre 75 74 79.5 ## 4 sally Post 78 78 83.0 ## 5 sue Pre 81 78 84.5 ## 6 sue Post 82 81 86.5 

期望的宽格式:

  Person Pre.Score1 Pre.Score2 Pre.Score3 Post.Score1 Post.Score2 Post.Score3 1 greg 80 78 84.0 79 80 84.5 2 sally 75 74 79.5 78 78 83.0 3 sue 81 78 84.5 82 81 86.5 

我可以通过为每个分数做这样的事情来做到这一点:

 spread(dat %>% select(Person, Time, Score1), Time, Score1) %>% rename(Score1_Pre = Pre, Score1_Post = Post) 

然后使用_join但似乎冗长,就像有一个更好的方法。

相关问题:
tidyr广泛到长与两个重复的措施
是否有可能使用与dcast类似的tidyr中的多列进行传播?

如果你想坚持tidyr/dplyr

 dat %>% gather(temp, score, starts_with("Score")) %>% unite(temp1, Time, temp, sep = ".") %>% spread(temp1, score) 

使用data.table包中的data.table

 library(data.table)#v1.9.5+ dcast(setDT(dat), Person~Time, value.var=paste0("Score", 1:3)) 

或从baseR reshape

 reshape(as.data.frame(dat), idvar='Person', timevar='Time',direction='wide') 

使用reshape2

 library(reshape2) dcast(melt(dat), Person ~ Time + variable) 

生产:

 Using Person, Time as id variables Person Post_Score1 Post_Score2 Post_Score3 Pre_Score1 Pre_Score2 Pre_Score3 1 greg 79 78 83.5 83 81 87.0 2 sally 82 81 86.5 75 74 79.5 3 sue 78 78 83.0 82 79 85.5