[英]R / dplyr / complex filter in function by string
I'm trying to hand over a filter with multiple arguments as a string to dplyr::filter within a function. 我正在尝试将具有多个参数的过滤器作为字符串传递给函数中的dplyr :: filter。 The answers I've seen so far all concern single filter argument, not multiple ones. 到目前为止,我所看到的答案都涉及单个过滤器参数,而不是多个过滤器参数。
Example: 例:
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)
The problem is not with the fact that you're using multiple conditions. 问题不在于您正在使用多个条件。 You can see that you get the same problem with only a single condition. 您可以看到只有一个条件就会遇到相同的问题。 The issue is that enquo
expects a bare expression, not a string. 问题是enquo
期望裸表达式而不是字符串。 So this returns the expected result: 因此,这将返回预期结果:
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
If you want to work with a string, you can use rlang::parse_expr
to turn a string into an expression for !!
如果要使用字符串,可以使用rlang::parse_expr
将字符串转换为!!
的表达式!!
to work with: 跟...共事:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.