使用dplyr将特定行重新排列到列中

时间:2015-11-12 19:41:48

标签: r dplyr

我试图以特定方式将行重新排列到列中(最好使用dplyr),但我真的不知道从哪里开始。我正在尝试为每个人(比尔或鲍勃)创建一行,并将所有这些人的值放在一行上。到目前为止我已经

df<-data.frame(
  Participant=c("bob1","bill1","bob2","bill2"),
  No_Photos=c(1,4,5,6)
)

res<-df %>% group_by(Participant) %>% dplyr::summarise(phot_mean=mean(No_Photos))

给了我:

  Participant mean(No_Photos)
       (fctr)           (dbl)
1       bill1               4
2       bill2               6
3        bob1               1
4        bob2               5

目标:

    mean_NO_Photos_1 mean_No_Photos_2
bob   1               5
bill  4               6

1 个答案:

答案 0 :(得分:1)

使用tidyrdplyr

library(tidyr)
library(dplyr)
df %>% mutate(rep = extract_numeric(Participant),
              Participant = gsub("[0-9]", "", Participant)) %>% 
       group_by(Participant, rep) %>%
       summarise(mean = mean(No_Photos)) %>%
       spread(rep, mean)

Source: local data frame [2 x 3]

  Participant     1     2
        (chr) (dbl) (dbl)
1        bill     4     6
2         bob     1     5