问题
Using the dplyr
package in R
, I want to pass a filter statement as a parameter in a function. I don't know how to evaluate the statement as code instead of a string. When I try the code below, I get an error message. I'm assuming I need a quosure or something, but I don't fully grasp that concept.
data("PlantGrowth")
myfunc <- function(df, filter_statement) {
df %>%
filter(!!filter_statement)
}
myfunc(PlantGrowth, "group %in% c('trt1', 'trt2')")
> Error: Argument 2 filter condition does not evaluate to a logical vector
# Want to do the same as this:
# PlantGrowth %>%
# filter(group %in% c('trt1', 'trt2'))
回答1:
You can use parse_expr
from rlang
library(dplyr)
myfunc <- function(df, filter_statement) {
df %>% filter(eval(rlang::parse_expr(filter_statement)))
}
identical(myfunc(PlantGrowth, "group %in% c('trt1', 'trt2')"),
PlantGrowth %>% filter(group %in% c('trt1', 'trt2')))
#[1] TRUE
The same can be done using infamous eval
and parse
.
myfunc <- function(df, filter_statement) {
df %>% filter(eval(parse(text = filter_statement)))
}
来源:https://stackoverflow.com/questions/61692367/how-to-pass-a-filter-statement-as-a-function-parameter-in-dplyr-using-quosure