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

前端 未结 6 1422
被撕碎了的回忆
被撕碎了的回忆 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:35

    As others have pointed out, you're looking for exists. Keep in mind that using exists with names used by R's base packages would return true regardless of whether you defined the variable:

    > exists("data")
    [1] TRUE
    

    To get around this (as pointed out by Bazz; see ?exists), use the inherits argument:

    > exists("data", inherits = FALSE)
    [1] FALSE
    
    foo <- TRUE
    > exists("foo", inherits = FALSE)
    [1] TRUE
    

    Of course, if you wanted to search the name spaces of attached packages, this would also fall short:

    > exists("data.table")
    [1] FALSE
    require(data.table)
    > exists("data.table", inherits = FALSE)
    [1] FALSE
    > exists("data.table")
    [1] TRUE
    

    The only thing I can think of to get around this -- to search in attached packages but not in base packages -- is the following:

    any(sapply(1:(which(search() == "tools:rstudio") - 1L),
               function(pp) exists(_object_name_, where = pp, inherits = FALSE)))
    

    Compare replacing _object_name_ with "data.table" (TRUE) vs. "var" (FALSE)

    (of course, if you're not on RStudio, I think the first automatically attached environment is "package:stats")

提交回复
热议问题