【发布时间】: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两次得到两个不同的结果?欺诈? -
问得好,我的测试数据集似乎有点问题,但下面的解决方案很棒。