使用dplyr将特定行重新排列为列
我试图以一种特定的方式将行重新排列成列(最好使用dplyr),但我真的不知道从哪里开始。我试图为每个人(比尔或鲍勃)创建一行,并将所有这些人的值放在一行上。到目前为止我有使用dplyr将特定行重新排列为列,r,dplyr,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_me
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))
目标:
使用
tidyr
和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
没问题,如果不需要,你可以使用小x删除评论。我不想直接编辑你的解决方案,但如果你不介意将
mean=mean(无照片)
更改为mean=mean(phot\u mean)
,这将解决问题(我更新了我的代码以匹配此)
mean_NO_Photos_1 mean_No_Photos_2
bob 1 5
bill 4 6
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