[英]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
根据此答案,您只需将普通字符串传递给filter_
函数即可,并且效果很好。
myfil <- function(df, fil) {
df <- filter_(df, fil)
df
}
我的结果:
> myfil(df, 'a > 3 & b > 2 & c < 8')
a b c
1 8 9 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.