【问题标题】:vectorising complex dplyr statement in R在 R 中矢量化复杂的 dplyr 语句
【发布时间】:2018-08-07 04:58:01
【问题描述】:

我正在尝试计算参加课程的学生人数,从能够参加课程的学生开始,并非所有学校都提供计算机,不同的学校提供​​英语,能够参加计算机和英语的学生会有所不同。例如。使用下面的测试数据,我们有:

df <- read.csv(text="school, student, course, result
      URN1,stu1,comp,A
      URN1,stu2,comp,B
      URN1,stu3,comp,C
      URN1,stu1,Eng,D
      URN1,stu1,ICT,E
      URN2,stu4,comp,A
      URN1,stu1,ICT,B
      URN2,stu5,comp,C
      URN3,stu6,comp,D
      URN3,stu6,ICT,E
      URN4,stu7,Eng,E
      URN4,stu8,ICT,E
      URN4,stu8,Eng,E
      URN5,stu9,comp,E
      URN5,stu10,ICT,E")

[1]“58.3333333333333 % 的可能学生参加了比赛”

[1]“33.3333333333333 % 的可能学生选择了英语”

[1]“38.4615384615385 % 的可能学生采用了 ICT”

我有以下循环(嘘!)来做到这一点:

library(magrittr)
library(dplyr)

for(c in unique(df$course)){
  # c <- "comp"
  #get URNs of schools offering each course
  URNs <- df %>% filter(course == c) %>% distinct(school) %$% school
  #get number of students in each school offering course c
  num_possible <- df %>% filter(school %in% URNs) %>% summarise(n = n()) %$% n
  #get number of students taking course c 
  num_actual <- df %>% filter(course == c) %>% summarise(n = n()) %$% n

  # get % of students taking course from those who could theoretically take c
  print(paste(c, "taken by", (100 * num_actual/num_possible), "% of possible students"))
}

但是想要将它全部矢量化,我无法将 num_possible 放入与 num_actual 相同的函数中:

df %>% group_by(course) %>% summarise(num_possible = somesubfunction(),
                                      num_actual = n())

somesubfunction() 应该返回可能参加课程 c 的学生人数

【问题讨论】:

  • 为什么stu1 使用ICT 两次得到两个不同的结果?欺诈?
  • 问得好,我的测试数据集似乎有点问题,但下面的解决方案很棒。

标签: r vector dplyr


【解决方案1】:

我知道这必须简化,但这是使用 的一种方法:

# load necessary packages
library( dplyr )

# calculate stats
df %>%
  group_by( school ) %>%
  summarise( Total_Students        = n()
             , Offer_Comp          = "comp" %in% unique( course ) 
             , Offer_English       = "Eng" %in% unique( course )
             , Offer_ICT           = "ICT" %in% unique( course )
             , Comp_Taken          = ifelse( test = Offer_Comp == TRUE
                                             , yes = length( course[ which( course == "comp" ) ] )
                                             , no = NA 
                                             )
             , English_Taken       = ifelse( test = Offer_English == TRUE
                                             , yes = length( course[ which( course == "Eng" ) ] )
                                             , no = NA 
             )
             , ICT_Taken           = ifelse( test = Offer_ICT == TRUE
                                             , yes = length( course[ which( course == "ICT" ) ] )
                                             , no = NA 
             ) ) %>%
  summarise( Comp_Possible         = sum( Total_Students[ which( Offer_Comp == TRUE ) ] )
             , Comp_Taken_Count    = sum( Comp_Taken, na.rm = TRUE )
             , Comp_Taken_Per      = Comp_Taken_Count / Comp_Possible * 100
             , English_Possible    = sum( Total_Students[ which( Offer_English == TRUE ) ] )
             , English_Taken_Count = sum( English_Taken, na.rm = TRUE )
             , English_Taken_Per   = English_Taken_Count / English_Possible * 100
             , ICT_Possible        = sum( Total_Students[ which( Offer_ICT == TRUE ) ] )
             , ICT_Taken_Count     = sum( ICT_Taken, na.rm = TRUE )
             , ICT_Taken_Per       = ICT_Taken_Count / ICT_Possible * 100 )

# final output
# A tibble: 1 x 9
# Comp_Possible Comp_Taken_Count Comp_Taken_Per English_Possible English_Taken_Count English_Taken_Per ICT_Possible ICT_Taken_Count ICT_Taken_Per
#         <int>            <int>          <dbl>            <int>               <int>             <dbl>        <int>           <int>         <int>
# 1         12                7           58.3                9                   3              33.3           13               5           38.5

# end of script #

【讨论】:

  • 您可能希望以长格式结束,并且没有在列名中编码课程。
【解决方案2】:

您正在对不同的变量级别进行总结。可能学生的数量是在学校级别上汇总的,而实际学生的数量是在课程级别上汇总的,其中级别没有嵌套在其中。

因此,我发现创建两个不同的数据框然后将它们连接在一起更容易,但我还将提供一个解决方案,在一个长时间调用中执行它。

library(dplyr)

先总结一个学校层面的数据:

df_school <- df %>% 
  group_by(school) %>% 
  summarise(n_students_school = n_distinct(student))

df_school
# A tibble: 5 x 2
#   school n_students_school
#   <fct>              <int>
# 1 URN1                   3
# 2 URN2                   2
# 3 URN3                   1
# 4 URN4                   2
# 5 URN5                   2

要为每所学校选择可能的课程,请将left_join 与原始df 一起使用,但仅使用school 和course 的distinct 组合:

df_possible <- df %>% 
  select(school, course) %>% 
  distinct() %>% 
  left_join(df_school, by = "school") %>% 
  group_by(course) %>% 
  summarise(n_possible = sum(n_students_school))

df_possible
# A tibble: 3 x 2
#   course n_possible
#   <fct>       <int>
# 1 comp            8
# 2 Eng             5
# 3 ICT             8

计算每门课程的实际学生人数:

df_actual <- df %>%
  group_by(course) %>% 
  summarise(n_actual = n_distinct(student))

df_actual
# A tibble: 3 x 2
#   course n_actual
#   <fct>     <int>
# 1 comp          7
# 2 Eng           3
# 3 ICT           4

将两个数据框加入最终数据框,计算课程中学生的百分比:

df_final <- left_join(df_possible, df_actual, by = "course") %>%
  mutate(percentage = n_actual/n_possible)

df_final
# A tibble: 3 x 4
#   course n_possible n_actual percentage
#   <fct>       <int>    <int>      <dbl>
# 1 comp            8        7      0.875
# 2 Eng             5        3      0.600
# 3 ICT             8        4      0.500

或者在一个不同分组的长时间通话中(学分转到@alistaire):

df %>% 
  group_by(school) %>% 
  group_by(school, course, n_students_school = n_distinct(student)) %>% 
  summarise(n_students_course = n_distinct(student)) %>% 
  group_by(course) %>% 
  summarise(n_possible = sum(n_students_school), 
            n_actual = sum(n_students_course), 
            percentage = n_actual / n_possible) 

在这里,通过将n_students_school = n_distinct(student) 添加到群组通话中,它会在为每门课程的学生总结时创建,然后不会被删除。

【讨论】:

  • 嗨,Kath,你得到的百分比与我的不符,
  • @pluke 是的,因为她没有将参加不同课程的学生算作同一学校的两个学生,或者同一课程的两次作为同一课程的两个学生。
  • @kath dplyr 有一个 n_distinct 函数,它等效于 length(unique(...))。为了进一步浓缩,df %&gt;% group_by(school) %&gt;% group_by(school, course, n_students_school = n_distinct(student)) %&gt;% summarise(n_students_course = n_distinct(student)) %&gt;% group_by(course) %&gt;% summarise(n_possible = sum(n_students_school), n_actual = sum(n_students_course), percentage = n_actual / n_possible)
  • @alistaire 感谢您告诉我n_distinct 函数和我的代码的较短版本。看到你所做的几个分组调用背后的逻辑真是令人着迷!
【解决方案3】:

您可以先创建一个辅助数据框,然后对其进行映射以获取可能的学生数量。考虑一下这个

school_students <- df %>% 
  group_by(school) %>% 
  summarise(students = n(), courses = paste0(unique(course), collapse = ", "))

df %>% 
  count(course) %>%
  mutate(possible = map_int(as.character(course), 
    ~sum(school_students[str_detect(school_students$courses, .), "students"]))) %>%
  mutate(pct = n / possible * 100)

# A tibble: 3 x 4
  course     n possible   pct
  <fct>  <int>    <int> <dbl>
1 comp       7       12  58.3
2 Eng        3        9  33.3
3 ICT        5       13  38.5

【讨论】:

  • 啊,这就是我可以使用 mutate 来缩短我的代码的方法!感谢您发帖。
  • 在我看来df %&gt;% group_by(school, course) %&gt;% summarise(actual = n()) %&gt;% group_by(course) %&gt;% summarise(actual = sum(actual)) 只能是count(df, course)?
  • 酷,现在更短了!请参阅下面的purrr-less 答案。
【解决方案4】:

如果您想尝试与 不同的东西,可以尝试:

library(data.table)

setDT(df)[, nb_stu:=.N, by=course] # how many students by course
df[, nb_stu_ec:=length(unique(student)), by=school] # how many students per school (!: Edited to avoid counting some students twice if they take multiple courses)

# finally compute the number of student for a course 
# divided by the number of students in the schools that have this course (sprintf is only for formating the result):
df[, sprintf("%.2f", 100*first(nb_stu)/sum(nb_stu_ec[!duplicated(school)])), by=course]
#   course    V1
#1:   comp 87.50
#2:    Eng 60.00
#3:    ICT 62.50

Nota Bene: 如果只在最后一步计算每门课程的学生人数,则可以少一步完成:

setDT(df)[, nb_stu_ec:=length(unique(student)), by=school]
df[, sprintf("%.2f", 100*(.N)/sum(nb_stu_ec[!duplicated(school)])), by=course]

#   course    V1
#1:   comp 87.50
#2:    Eng 60.00
#3:    ICT 62.50

【讨论】:

    【解决方案5】:

    我会先计算一个频率表——你不需要在这里使用原始数据:

    ft <- with(df, as.matrix(table(school, course)))
    # converting table to matrix to make it easier to handle
    

    那么你可以使用for或sapply或apply进行除法和乘法:

    sapply(1:ncol(ft), function(x) {
      k <- ft[, x]
      sum(k) / sum(ft[k!=0,])*100
    })
    

    或者(这是一个简单的问题,所以使用多行是浪费行):

    apply(ft, 2, function(k) sum(k) / sum(ft[k!=0,]))*100
    #      comp      Eng      ICT 
    #  58.33333 33.33333 38.46154 
    

    【讨论】:

      【解决方案6】:

      另一个简短的dplyr 答案。加入课程和学校概况,然后是简单的summarise。

      library(dplyr)
      
      left_join(
        count(df, course),
        df %>% group_by(school) %>% transmute(s = n(), course) %>% distinct()
      ) %>% 
        group_by(course) %>% 
        summarise(actual = first(n),
                  total = sum(s),
                  perc = actual / total * 100)
      

      这再现了你的答案:

      # A tibble: 3 x 4
        course actual total  perc
        <fct>   <int> <int> <dbl>
      1 comp        7    12  58.3
      2 Eng         3     9  33.3
      3 ICT         5    13  38.5
      

      但您可能不想重复计算学生人数,因此请寻找不同的学生:

      left_join(
        count(df, course),
        df %>% group_by(school) %>% transmute(s = n_distinct(student), course) %>% distinct()
      ) %>% 
        group_by(course) %>% 
        summarise(actual = first(n),
                  total = sum(s),
                  perc = actual / total * 100)
      
      # A tibble: 3 x 4
        course actual total  perc
        <fct>   <int> <int> <dbl>
      1 comp        7     8  87.5
      2 Eng         3     5  60.0
      3 ICT         5     8  62.5
      

      【讨论】:

      • 第二个答案仍然算std1 两次,因为他在ICT 中有两个results。我不相信这些数据有意义,但还有另一个人可以参加这门课程。
      • 嗯,好的。那我也不是很懂数据。
      【解决方案7】:

      这重现了您的预期输出,但在您多次计算学生时可能会出错:

      df %>%
        count(school,course) %>%
        left_join(df %>% count(school),by="school") %>%
        group_by(course) %>%
        summarize(num_actual = sum(n.x), pc = num_actual/sum(n.y))
      
      # # A tibble: 3 x 3
      #   course num_actual        pc
      #   <fctr>      <int>     <dbl>
      # 1   comp          7 0.5833333
      # 2    Eng          3 0.3333333
      # 3    ICT          5 0.3846154
      

      这将是正确的答案:

      df %>%
        count(school,course) %>%
        left_join(distinct(df[c("school","student")]) %>% count(school),by="school") %>%
        group_by(course) %>%
        summarize(num_actual = sum(n.x), pc = num_actual/sum(n.y))
      
      # # A tibble: 3 x 3
      #   course num_actual    pc
      #   <fctr>      <int> <dbl>
      # 1   comp          7 0.875
      # 2    Eng          3 0.600
      # 3    ICT          5 0.625
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        • 2021-11-30
        • 2016-05-30
        • 1970-01-01
        • 2020-01-17
        • 1970-01-01
        • 2018-10-01
        相关资源
        最近更新 更多