简体   繁体   中英

rearrange specific rows into columns using dplyr

I am trying to rearrange rows into columns in a specific way (preferably using dplyr) but I dont really know where to start with this. I am trying to create one row for each person (Bill or Bob) and have all of that persons values on one row. So far I have

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))

which gives me:

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

GOAL:

    mean_NO_Photos_1 mean_No_Photos_2
bob   1               5
bill  4               6

Using tidyr and dplyr :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM