How to check existence of an input argument for R functions

danioyuan picture danioyuan · Mar 26, 2012 · Viewed 21.8k times · Source

I have a function defined as

myFun <- function(x, y, ...) {
  # using exists
  if (exists("z")) { print("exists z!") }
  # using missing
  try(if (!missing("z")) { print("z is not missing!") }, silent = TRUE)
  # using get
  try(if (get("z")) { print("get z!") }, silent = TRUE)

  # anotherFun(...)
}

In this function, I want to check whether user input "z" in the argument list. How can I do that? I tried exists("z"), missing("z"), and get("z") and none of them works.

Answer

GSee picture GSee · Mar 27, 2012

I think you're simply looking for hasArg

myFun <- function(x, y, ...) { 
  hasArg(z)
}

> myFun(x=3, z=NULL)
[1] TRUE

From ?hasArg:

The expression hasArg(x), for example, is similar to !missing(x), with two exceptions. First, hasArg will look for an argument named x in the call if x is not a formal argument to the calling function, but ... is. Second, hasArg never generates an error if given a name as an argument, whereas missing(x) generates an error if x is not a formal argument.