Function: ignorable input

Hi,

I want to create an if statement for the case if an input variable is ignored to specify in a function (so create a default value to an input). Minimalist example is enclosed.

Thank you for your help in advance,
Marcell

test_fun <- function(a, b) {
  if (!exists(b, mode = "function")) {
    b = 3
    return(a + b)
  }
}

test_fun(a = 3)
#> Error in exists(b, mode = "function"): argument "b" is missing, with no default

Created on 2020-08-22 by the reprex package (v0.3.0)

Do you mean you want to have 3 be the default value for b if it isn't supplied? If so, you can define test_fun with default values:

test_fun <- function(a,b=3){
  return(a+b)
}

If you want to just check if a variable is supplied, you can either set it's default value to be NULL and check for this:

test_fun <- function(a,b=NULL){
  if(is.null(b)){
    b <- 3
    # More code here
  } else {
    #Do other code here
  }
  return(a+b)
}

or just check if the value is missing()

test_fun <- function(a,b){
  if(missing(b)){
    b <- 3
    # More code here
  } else {
    #Do other code here
  }
  return(a+b)
}

Although these two options behave essentially the same way (barring the case of deliberately supplying b = NULL), the implication of their use is different. Using NULL implies that it's acceptable for no value to be supplied and your function knows how to handle it. Using missing() implies that the check is there as a back-up and the user is still expected to supply this value.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.