r - 如何使用 quosure 在 dplyr 中将过滤器语句作为函数参数传递
问题描述
使用中的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'))
解决方案
你可以使用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
使用 臭名昭著 eval
和parse
.
myfunc <- function(df, filter_statement) {
df %>% filter(eval(parse(text = filter_statement)))
}
推荐阅读
- angularjs - 当它不是angularjs中的json时响应的奇怪行为得到
- python - IDE 中的异常对象和缺少 __context__ 和 __cause__ 属性
- python-2.7 - 在 Centos 7 上使用 python 2.7 将 gradle 添加到 PATH 变量
- django - 如何创建查询集以过滤键名中带有 __ 的 jsonb 字段
- sybase - 我使用什么 SQL 来转换(大)日期时间以显示微秒?
- python - 我在使用模板视图时遇到此错误
- regex - 在 Apache 2.4 中使用 REQUEST_URI 和 ap_expr 设置 Header
- javascript - 在 Javascript 中实现多线程合并排序的问题
- ms-access - 根据 Access 中的是/否答案将多个数字字段添加在一起
- javascript - TypeError:试图分配给只读属性。【批量写入、云火库】