I want to create a function to count the values in a certain variable in a subsetted dataset, but my function is not working as it supposed to.
selected_cyl_6 <- subset(mtcars, mtcars$cyl==6)
selected_cyl_4 <- subset(mtcars, mtcars$cyl==4)
count <- function(group,variable) {
sum(group$variable == 4)
}
count(selected_cyl_6,gear)
# [1] 0
The answer should be 4. However, if I use the sum directly I get the correct answer
sum(selected_cyl_6$gear==4)
# [1] 4
Another example
count(selected_cyl_4,gear)
# [1] 0
sum(selected_cyl_4$gear==4)
# [1] 8
What am I doing wrong?