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

Solution 1:

You want exists():

R> exists("somethingUnknown")
[1] FALSE
R> somethingUnknown <- 42
R> exists("somethingUnknown")
[1] TRUE
R> 

Solution 2:

See ?exists, for some definition of "...is defined". E.g.

> exists("foo")
[1] FALSE
> foo <- 1:10
> exists("foo")
[1] TRUE

Solution 3:

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… :-(