I have a function with an argument subset that has the default value of NULL. Within the function if subset is NULL I do not want to add a conditional pipe. Otherwise, I want to use the value of subset within the pipe:
library(tidyverse)
f <- function(subset = NULL){
iris %>%
{if (is.null(substitute(subset))) . else filter(., {{ subset }} < 2.2)}
}
f() # gives error posted below
## Desired output: entire iris dataset
f(subset = Sepal.Width) # works
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5 2 3.5 1 versicolor
However, using the curly brackets, {{ subset}} is evaluating too early when subset = NULL and is trying to filter where NULL < 2.2. f() returns the following error:
Error: Problem with
filter()input..1.x Input
..1must be of size 150 or 1, not size 0.i Input
..1isNULL < 2.2.