I want to pass in an expression as a character vector for a function in R
For example,
library(dplyr)
filter_function <- function(data, filter_exp) {
data %>%
filter( {{ filter_exp }})
}
filter_function(mtcars, filter_exp = cyl == 6)
However, I would like it to work where the filter_exp
argument requires quotation marks. For example,
filter_function(mtcars, filter_exp = cyl == 6) # works
filter_function(mtcars, filter_exp = "cyl == 6") # does not work
This is a way that seems to work, but this doesn't seem to be the current suggested way of programming in dplyr from the "Programming with dplyr" vignette.
filter_function_2 <- function(data, filter_exp) {
filter(data, !! rlang::parse_expr(filter_exp))
}
filter_function_2(mtcars, filter_exp = "cyl == 6")
Is this still the most sensible way of doing this or is there a better way to read in an expression with quotations using the current suggested way of programming in dplyr?