首页 > 解决方案 > 如何使用 quosure 在 dplyr 中将过滤器语句作为函数参数传递

问题描述

使用中的dplyrR,我想将过滤器语句作为函数中的参数传递。我不知道如何将语句评估为代码而不是字符串。当我尝试下面的代码时,我收到一条错误消息。我假设我需要一个 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'))

标签: rdplyrrlangquosure

解决方案


你可以使用parse_exprrlang

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

使用 臭名昭著 evalparse.

myfunc <- function(df, filter_statement) {
   df %>% filter(eval(parse(text = filter_statement)))
}

推荐阅读