R

Asked • 10/05/19

Correct way to specifiy optional arguments in R functions?

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.5The 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.5Personally 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".

1 Expert Answer

By:

Justin R. answered • 11/12/20

Tutor
5.0 (170)

Ph.D. in Geophysics. Teaching at the university level since 1990.

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.