keszei
keszei

Reputation: 51

Check if the passed argument exists

I am trying to check if a variable passed as argument to a function exists. Based on the answer to this question I have the following:

myfunction <- function(x) {
  stopifnot(exists(deparse(substitute(x))))
}

However, it does not work if the argument is an expression to be evaluated:

a=c(1:10)
myfunction(a+10)

How can I make sure that I capture non-existent variables if the argument is not just a variable?

Upvotes: 3

Views: 476

Answers (1)

javlacalle
javlacalle

Reputation: 1049

One option is combining match.call (returns the call to the function) and all.vars (returns the names in an expression). Try this:

fcn <- function(x) {
  varnames <- all.vars(match.call())
  for (x in varnames)
    stopifnot(exists(x))
}

fcn(a) # returns error, as expected
#Error: exists(x) is not TRUE

# create "a"
a <- 2
fcn(a + 1) # no error returned since "a" exists

Similarly,

fcn(a + b) # error returned since "b" does not exist
#Error: exists(x) is not TRUE
b <- 4
fcn(a + b) # no error since "b" now exists

Upvotes: 1

Related Questions