[R] Testing for existence of object within a function

Eli Holmes e2holmes at gmail.com
Fri Oct 8 01:27:11 CEST 2010


I'm trying to test for the existence of an object within a function,
but despite searching the help files and R-list, I can't figure out
how to do it.

Here is some test code:

#-------------------------
a=1 #now I have a in the global environment

tst <- function(a,b=1) {
# but a is not in the local function environment
print(exists("a", inherits=FALSE)) #This is how I think I should be
able to test if it is in the local function environment
print(a)
}
tst()
#----------------------

#Here's the output
[1] TRUE
Error in print(a) : argument "a" is missing, with no default

It says TRUE, even though I specified inherits=FALSE and "a" is not in
the function environment.  I've tried to pass in where and envir
arguments to exists() but I haven't been able to solve the problem.

Thanks in advance.



More information about the R-help mailing list