Quantcast
Channel: How to check if object (variable) is defined in R? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

Answer by sbaldrich for How to check if object (variable) is defined in R?

$
0
0

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] FALSEfoo <- 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] FALSErequire(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")


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>