r - R/dplyr/complex filter in function by string
问题描述
我正在尝试将具有多个参数的过滤器作为字符串移交给函数内的 dplyr::filter 。到目前为止,我看到的答案都是关于单个过滤器参数,而不是多个。
例子:
myfil <- function(df, fil) {
quo_fil <- enquo(fil)
df <- filter(df, !! quo_fil)
df
}
set.seed(25)
df <- data.frame(a = sample(10, 10), b = sample(10, 10), c = sample(10, 10))
#works
filter(df, a > 3 & b > 2 & c < 8)
a b c
1 5 4 1
2 7 10 5
3 9 5 2
4 6 6 3
# does not work
f <- "a > 3 & b > 2 & c < 8"
myfil(df, f)
解决方案
问题不在于您使用多个条件这一事实。您可以看到只有一个条件会遇到相同的问题。问题是enquo
需要一个裸表达式,而不是字符串。所以这会返回预期的结果:
myfil(df, a > 3 & b > 2 & c < 8)
a b c
1 5 4 1
2 7 10 5
3 9 5 2
4 6 6 3
如果要使用字符串,可以使用rlang::parse_expr
将字符串转换为表达式!!
以使用:
myfil <- function(df, fil) {
quo_fil <- rlang::parse_expr(fil)
filter(df, !!quo_fil)
}
f <- "a > 3 & b > 2 & c < 8"
myfil(df, f)
a b c
1 5 4 1
2 7 10 5
3 9 5 2
4 6 6 3
推荐阅读
- unicode - 在 Windows 10 cmd 中显示 unicode 字符
- visual-studio - TFS/C#:在构建过程中记录自定义警告
- php - 为什么 laravel push 给我一个错误 1364:字段 'question_entity_id' 没有默认值?
- sql - 一组结果中的sql分组
- javascript - 如何使用 Xpath 从嵌套表中获取行数?
- apache - 如何使用 htaccess 将视频流重定向到另一个域
- cloud - 试图深入理解云计算中“资源池”的概念
- .net - 如何根据文本长度计算datagridview行高
- node.js - 根据实际和预期数据重构 json
- bash - 期望脚本发送重新启动从未被机器处理