【问题标题】:Group by and conditions in RR中的分组和条件
【发布时间】:2021-11-25 12:11:17
【问题描述】:

我有一个名称、课程、课程和完成情况相似的数据框。

name <- c("John", "John", "John", "Sam", "Sam")
course <- c("Driving", "Driving", "Driving", "Cycling", "Cycling")
lesson <- c("Gears", "Parking", "Overtaking", "Balancing", "Turning")
completion <- c(1, 0, 1, 1, 1)
df_school <- data.frame(name, course, lesson, completion)

如果学生没有完成任何课程,我想将所有完成更改为 0。输出应该是:

name <- c("John", "John", "John", "Sam", "Sam")
course <- c("Driving", "Driving", "Driving", "Cycling", "Cycling")
lesson <- c("Gears", "Parking", "Overtaking", "Balancing", "Turning")
completion <- c(0, 0, 0, 1, 1)
df_completed <- data.frame(name, course, lesson, completion)

谢谢

【问题讨论】:

    标签: r conditional-statements


    【解决方案1】:

    dplyr

    df_school %>%
      group_by(name) %>%
      mutate(completion = +all(completion == 1))
    
      name  course  lesson     completion
      <chr> <chr>   <chr>           <dbl>
    1 John  Driving Gears               0
    2 John  Driving Parking             0
    3 John  Driving Overtaking          0
    4 Sam   Cycling Balancing           1
    5 Sam   Cycling Turning             1
    

    【讨论】:

      【解决方案2】:

      dplyr

      library(dplyr)
      df_school %>% group_by(name) %>%
        mutate(completion=+(length(completion) == sum(completion)))
      

      输出:

        name  course  lesson     completion
        <chr> <chr>   <chr>           <int>
      1 John  Driving Gears               0
      2 John  Driving Parking             0
      3 John  Driving Overtaking          0
      4 Sam   Cycling Balancing           1
      5 Sam   Cycling Turning             1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 2013-08-09
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多