Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...