[R] Testing for existence of object within a function

Eli Holmes e2holmes at gmail.com
Fri Oct 8 22:05:57 CEST 2010

Thanks for the help.  After looking over the answers, I've come up
with some revised code:

# To simply test if an argument was passed in, missing() can be used
# However, if arg defined later, missing() will return TRUE instead of false

a=1 #put a in global environment
tst <- function(a,b=1) {
if(missing("a")){ print("a is missing") }else print("a is not missing")
a=1 #a now defined in function environment
if(missing("a")){ print("a is missing") }else print("a is not missing")

# To show the function LOCAL variables, you can use ls() within the function
# However this will not tell you if the value for the local variable
is missing (no value)

a=1; c=1 #put a and c in user workspace environment
tst <- function(a,b=1) {
d = 1 #put d in the local function environment
print( ls() ) #all the local function variables: c doesn't show up
since it is not in the local environment
#but the value for a is missing
#formals shows just the function arguments (not all function
variables); notice "a" is blank
print( formals("tst") )
#Sadly the following does not work since missing(a) and missing("a")
are the same. So missing(el) is then always FALSE
for( el in ls() ){
if(missing(el)) print(paste(el,"is missing"))
#You have to actually do this command
if(missing("a")) print("a is missing")
#which might cause trouble if you don't know what the argument names
are ahead of time (if say the function is being written by a script)

#But you can at least do this
need.these.local = c("a","c","g") #c is in the global envir but I want
to make sure it is in the local envir
if( !all(need.these.local %in% ls()) ) print("missing something you need")

My original note suggested that exists(x,inherits=FALSE) was not
working as I expected, which was that
it was testing existence in the local function environment.  In fact,
this command is working as expected, but I didn't know
that an object could exist and have "no value".

I'm still trying to sort out if I can tell the function not to use
values in the user workspace if they don't exist locally in a
function, i.e. a "use local variables only" option when defining a
function. Obviously, I could go to a style of programming where
I define all local function variables at the top of my function and
set them, somehow, to a value that will crash the code if I forget to
reset them later in the function, but it would be easier if I could
tell the function not to look for variables in the user workspace.

More information about the R-help mailing list