How to check if object (variable) is defined in R?
You want exists()
:
R> exists("somethingUnknown")
[1] FALSE
R> somethingUnknown <- 42
R> exists("somethingUnknown")
[1] TRUE
R>
See ?exists
, for some definition of "...is defined". E.g.
> exists("foo")
[1] FALSE
> foo <- 1:10
> exists("foo")
[1] TRUE
if you are inside a function, missing() is what you want.
exchequer = function(x) {
if(missing(x)){
message("x is missing… :-(")
}
}
exchequer()
x is missing… :-(