I\'d like to check if some variable is defined in R - without getting an error. How can I do this?
My attempts (not successful):
> is.na(ooxx)
Err
There may be situations in which you do not exactly know the name of the variable you are looking for, like when an array of results have been created by a queuing system. These can possibly be addressed with "ls" and its argument "pattern" that expects a regular expression.
The "exists" function could be reimplemented that way as
exists <-function(variablename) {
#print(ls(env=globalenv()))
return(1==length(ls(pattern=paste("^",variablename,"$",sep=""),env=globalenv())))
}
While preparing this answer, I was a bit surprised about the need for the need of the specification of the environment when invoking ls() from within a function. So, thank you for that, stackoverflow! There is also an "all.names" attribute that I should have set to true but have omitted.