I would like to calculate the average exam score of each student and add this as a new column to a data frame:
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)))
But the code above gives the following error:
Error in Ops.factor(student_examn, my_students) :
level sets of factors are different
I assume it has to do with filter(student_exam == my_students). How would I do this in dplyr?
filtertries to do. All your students have a score in your example. Something like this would work in your case:df = data.frame(student_exam, score_exam); df %>% group_by(student_exam) %>% mutate(avg_score = mean(score_exam)) %>% ungroup()