I want to define a simple function that will filter a data frame, similar to something you might do in SPSS with the "Select Cases" menu option.
Here is what I would type in the console to filter it using the subset function if I wanted to only keep cases where q3a is 1: subset(df, q3a==1)
. This will run with no problem and returns a data frame including only those cases where q3a is 1.
However, when I use the following function, I get an error:
filter <- function(frame, var, val) {
newFrame <- subset(frame, var==val)
return(newFrame)
}
When I try to run filter(df, q3a, 1)
, R throws me the following error: Error in eval(expr, envir, enclos) : object 'q3a' not found
.
I can't see what the problem is here. It seems like the function should just directly pass the arguments to the subset function, but clearly that's not happening.