我想计算每个学生的平均考试成绩,并将其作为新列添加到数据框中:
library(dplyr)
my_students <- c("John", "Lisa", "Sam")
student_exam <- c("John", "Lisa", "John", "John")
score_exam <- c(7, 6, 7, 6)
students <- as.data.frame(my_students)
scores <- as.data.frame(student_exam)
scores <- cbind(scores, score_exam)
new_frame <- students %>% mutate(avg_score = (scores %>% filter(student_exam == my_students) %>% mean(score_exam)))
但是上面的代码给出了以下错误:
Error in Ops.factor(student_examn, my_students) :
level sets of factors are different
我认为它与过滤器(student_exam == my_students)
有关。我将如何在dplyr中做到这一点?
答案 0 :(得分:2)
您需要确保定义两个数据帧,它们的匹配列名为“ name”。然后,您可以使用group_by并汇总以按学生对分数进行分组,并汇总每个学生的平均值。此解决方案有一个警告,告诉您应该注意,并非班上的每个学生都有平均考试成绩。结果,Sam的平均得分为NA。
library(dplyr)
my_students <- c("John", "Lisa", "Sam")
student_exam <- c("John", "Lisa", "John", "John")
score_exam <- c(7, 6, 7, 6)
students <- data.frame("name" = as.character(my_students))
scores <- data.frame("name" = as.character(student_exam), "score" = score_exam)
avg_scores <- scores %>%
group_by(name) %>%
summarize(avgScore = mean(score)) %>%
right_join(students)