How to pass a filter statement as a function parameter in dplyr using quosure [duplicate]

白昼怎懂夜的黑 提交于 2021-02-05 07:55:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!