使用 tidyverse 将逻辑操作编程为参数

Programming logical operations as arguments using tidyverse

如何使用 tidyverse 函数为 R 中的函数提供逻辑参数? 不允许用户更改逻辑运算符,它假设函数的用户总是想要 ==.

请参阅下面的代码示例和到目前为止的尝试。

# example data
library(tidyverse)
dat <- tibble(x = letters[1:4], y = 1:4, z = 5:8)

# what I want to do is have a function that passes arguments to filter()
# so that I can flexibly subset data:
dat %>% 
  filter(x == "a" | y < 2)

dat %>% 
  filter(x == "b" & y < 1)

dat %>% 
  filter(y == max(y))

# what would I pass to lgl to do this in a function?
# I want to be a ble to feed in different logical expressions, notalways using
#    the same variables and operations, like the documentation for filter()
#    demonstrates

# tries so far:
fun <- function(dat, lgl) filter(dat, lgl)
fun(dat, x == "a" | y < 2)

fun <- function(dat, lgl) filter(dat, quo(lgl))
fun(dat, x == "a" | y < 2)

fun <- function(dat, lgl) filter(dat, quos(lgl))
fun(dat, x == "a" | y < 2)

fun <- function(dat, lgl) filter(dat, !!sym(lgl))
fun(dat, 'x == "a" | y < 2')

fun <- function(dat, lgl) filter(dat, !!!syms(lgl))
fun(dat, 'x == "a" | y < 2')

fun <- function(dat, lgl) filter(dat, expr(lgl))
fun(dat, x == "a" | y < 2)

fun <- function(dat, lgl) filter(dat, eval(lgl, envir = parent.frame()))
fun(dat, x == "a" | y < 2)

在编写示例时,我找到了解决方案。但我想我会 post 以防万一有人 运行 遇到类似的问题:

> fun <- function(dat, ...) filter(dat, ...)
> fun(dat, x == "a" | y < 2)
# A tibble: 1 x 3
  x         y     z
  <chr> <int> <int>
1 a         1     5

不过,这在某种程度上是一种解决方法,因为它实际上并不解释表达式,而只是传递参数。看到另一个解决方案也会很有趣。