R – “Correct” way to specifiy optional arguments in R functions

functionr

I am interested in what is the "correct" way to write functions with optional arguments in R.
Over time, I stumbled upon a few pieces of code that take a different route here, and I couldn't find a proper (official) position on this topic.

Up until now, I have written optional arguments like this:

fooBar <- function(x,y=NULL){
  if(!is.null(y)) x <- x+y
  return(x)
}
fooBar(3) # 3
fooBar(3,1.5) # 4.5

The function simply returns its argument if only x is supplied. It uses a default NULL value for the second argument and if that argument happens to be not NULL, then the function adds the two numbers.

Alternatively, one could write the function like this (where the second argument needs to be specified by name, but one could also unlist(z) or define z <- sum(...) instead):

fooBar <- function(x,...){
  z <- list(...)
  if(!is.null(z$y)) x <- x+z$y
  return(x)
}
fooBar(3) # 3
fooBar(3,y=1.5) # 4.5

Personally I prefer the first version. However, I can see good and bad with both. The first version is a little less prone to error, but the second one could be used to incorporate an arbitrary number of optionals.

Is there a "correct" way to specify optional arguments in R? So far, I have settled on the first approach, but both can occasionally feel a bit "hacky".

Best Solution

You could also use missing() to test whether or not the argument y was supplied:

fooBar <- function(x,y){
    if(missing(y)) {
        x
    } else {
        x + y
    }
}

fooBar(3,1.5)
# [1] 4.5
fooBar(3)
# [1] 3
Related Question