Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

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 the 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 options.

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 Answer

0 votes
by
edited by

You can use the missing function to check whether or not  an argument was passed to the function or not.

For example:

To find sum of squares of two numbers if both are passed, otherwise the square of number that is passed:

sqrFun <- function(x,y){

  if(missing(y)) {

    x^2

  } else {

    x^2 + y^2

  }

}

Output:

sqrFun(9,8)

[1] 145

> sqrFun(3)

[1] 9

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...