How to check if object (variable) is defined in R?

前端 未结 6 1416
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 20:02

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         


        
6条回答
  •  天涯浪人
    2020-11-28 20:49

    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.

提交回复
热议问题