Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a function using a ! logical operator before an ellipsis ....

Below is a simple example:

library(tidyverse)

myfun <- function(data, ...) {
  filter(data, !(...))
}

The function does not work and throw the following error:

> myfun(iris, Sepal.Width < 4)
Error: Problem with `filter()` input `..1`.
x object 'Sepal.Width' not found
? Input `..1` is `!(...)`.

How can I make it work?

Note that for my purpose, I have to negate the condition inside myfun.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's the rlang approach:

myfun <- function(data, ...) {
  x <- rlang::enquos(...)
  filter(data, !(!!!x))
}

myfun(iris, Sepal.Width < 4)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.8         4.0          1.2         0.2  setosa
2          5.7         4.4          1.5         0.4  setosa
3          5.2         4.1          1.5         0.1  setosa
4          5.5         4.2          1.4         0.2  setosa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...