【问题标题】:rearrange specific rows into columns using dplyr使用 dplyr 将特定行重新排列到列中
【发布时间】:2015-11-12 19:41:47
【问题描述】:

我正在尝试以特定方式将行重新排列成列(最好使用 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

【问题讨论】:

    标签: r dplyr


    【解决方案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
    

    【讨论】:

    • 没问题,不需要的可以用小x删除cmets
    • 我不想直接编辑您的解决方案,但如果您不介意将 mean=mean(No_Photos) 更改为 mean=mean(phot_mean) 将解决问题(我更新了我的代码以匹配此问题)
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2021-12-23
    • 1970-01-01
    • 2022-01-24
    • 2013-10-26
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多