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

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

r - Using a "not" operator before an ellipsis

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...