I have the following function:
my_fct <-
function(input1, input2, input3) {
output <- df %>%
filter(x = input1 | x = input2 | x = input3
)
}
with let's say input1 = c(1:10), input2 = c(1:10), input3 = c(1:10)
In some occassions, I only need one or two of the three inputs, like
output <- my_fct(3, 5)
Unfortunately, my approach requires to insert exactly three arguments. Is there a way to create a function, in which the argument input can vary?
I really appreciate your help, thanks
I'm going to demonstrate using this dataset:
Do you mean
filter(x == input1 | ...)?x=input1is unlikely to work as I'm inferring.Functions should not be breaking scope to assume that an object is visible in the calling environment (
dfhere). Doing it this way breaks reproducibility and can make troubleshooting more difficult. In this case, it can be more difficult since ifdfdoes not exist, the error will likely referencefunctionorclosureand not just sayobject 'df' not found`, which can be confusing if you aren't familiar with what's going on.For the examples below, I'll explicitly add
.dataas the first argument to work around this. (Making it the first argument means it'll play nicely with dplyr.) Similarly, I'll guard against"x"not being found in the data ... it might be useful to read https://dplyr.tidyverse.org/articles/programming.html for this, though a bit more work and out of scope for this answer.We can use default values of
NULL, perhaps(We can't use
is.null(input1) | x == input1since both sides of|are always run, andx == NULLreturns a 0-length vector instead of what we need.)If
input*are always going to be length-1 vectors, we can simplify it a little withIf you are looking for something a bit more flexible (such as someday wanting
input4as well, then perhaps