I'm trying to write a function that allows me to input text strings for field
, operator
, and value
, and return a simple dplyr::filter
function that I can then apply to a dataset.
Example:
library(dplyr)
field <- "Species"
operator <- "=="
value <- "virginica"
myfun <- substitute(
function(x) filter(x, EXPR(FIELD, VALUE)),
list(
FIELD = as.symbol(field),
EXPR = as.symbol(operator),
VALUE = value
)
)
myfun
function(x) filter(x, Species == "virginica")
So far, so good, right? Looks like we're all ready to roll. But not so fast:
> myfun(iris)
Error in myfun(iris) (from foo.R!10Zf0E#19) : could not find function "myfun"
If I type class(myfun)
, it turns out that I've created something called a call
. But I really wanted a function. Is there a way to turn the call into a function, or rewrite the above code so that I actually end up with a working function?