首页 > 解决方案 > 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)

标签: rstringfilterdplyr

解决方案


问题不在于您使用多个条件这一事实。您可以看到只有一个条件会遇到相同的问题。问题是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

推荐阅读