How do I feed logical arguments to functions in R, programming with tidyverse functions? This related question does not allow the user to change the logical operator, it assumes the user of the function always wants ==
.
See code below for example and attempts so far.
# 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)
As I as writing the example out, I found the solution. But I thought I would post here just in case anyone ran into a similar issue:
> 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
It is somewhat of a workaround, though, as it in't actually interpreting the expression, but just passing the argument along. Would be interesting to see another solution, as well.