如何使用 quosure 将过滤器语句作为 dplyr 中的函数参数传递

pln*_*nnr 1 r dplyr rlang quosure

使用dplyr中的包R,我想将过滤器语句作为函数中的参数传递。我不知道如何将语句评估为代码而不是字符串。当我尝试下面的代码时,我收到一条错误消息。我假设我需要一个 quosure 或其他东西,但我没有完全理解这个概念。

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'))
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 7

您可以使用parse_expr来自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
Run Code Online (Sandbox Code Playgroud)

使用inknown eval和也可以完成同样的操作 parse

myfunc <- function(df, filter_statement) {
   df %>% filter(eval(parse(text = filter_statement)))
}
Run Code Online (Sandbox Code Playgroud)