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"
)