如何使用quosure将filter语句作为dplyr中的函数参数传递 [英] How to pass a filter statement as a function parameter in dplyr using quosure

查看:48
本文介绍了如何使用quosure将filter语句作为dplyr中的函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 R 中的 dplyr 包,我想将过滤器语句作为函数中的参数传递.我不知道如何将语句评估为代码而不是字符串.当我尝试下面的代码时,我收到一条错误消息.我以为我需要担保,但我没有完全掌握这个概念.

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'))

推荐答案

您可以使用 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

可以使用臭名昭著 eval parse .

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

这篇关于如何使用quosure将filter语句作为dplyr中的函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆