I'm just beginning to learn how to write my own functions, and I'm trying to write a compute_means
function for a very specific kind of data frame. This question seems similar, but it didn't get an answer and I haven't found anything else that seems to address it.
My data looks something like this:
student <- c("alw", "alw", "bef", "bef")
semester <- c("autumn", "spring", "autumn", "spring" )
test1 <- c(87, 88, 90, 78)
test2 <- c(67, 78, 81, 88)
x <- data.frame(student, semester, test1, test2)
What I would like to be able to do is to write a function where I can compute the means, either grouped by semester, or by student and semester, or for just a single student. I can get the groups of students to work, but I'm getting stuck when I try to compute the means for the test scores for a single student. Here is what i have so far (the problematic section is the else if
part):
compute_means <- function(df, student = NA, separate = FALSE){
if (!separate & is.na(student)){
df %>%
group_by(semester) %>%
summarise(count = n(), test1 = mean(test1), test2 = mean(test2)) %>%
mutate(students = c("AllStudnts")) %>%
select(students, semester: test2)
}
else if(!separate & !is.na(student)){
df %>%
filter(student == student) %>%
group_by(semester) %>%
summarise(count = n(), test1 = mean(test1), test2 = mean(test2)) %>%
mutate(student = student)
}
else{
df %>%
group_by(student, semester) %>%
summarise(count = n(), test = mean(test1), test2 = mean(test2))
}
}
compute_means(x)
does what i think it would: I get the mean for all students by semester. compute_means(x, separate = TRUE)
also does what I think it would. However, compute_means(x, student = "alw")
doesn't do what I thought it would. Instead of getting alw
, I get the same thing that I would if I didn't have filter().
. I imagine that it must be easy to do this, but I can't figure out what it would be.