exists
Determine if an Object is Defined

Description

Looks for an object with the given name to check whether it has been defined and returns it.

Usage

exists(x, where = -1, envir = if (missing(frame)) as.environment(where)
    else sys.frame(frame), frame, mode = "any", inherits = TRUE)
get0(x, envir = pos.to.env(-1L), mode = "any", inherits = TRUE,
    ifnotfound = NULL)

Arguments

x a character string representing the object to be found/gotten.
where specifies the environment in which to find/get the object. exists accepts several ways to specify the environment. See Details for more information.
envir an environment object. An alternative way to specify the environment to find the object.
frame a frame used in calling list. If provided, the default value of envir is set to sys.frame(frame).
mode a character string giving the mode wanted for the object. The default, "any", means that any mode is acceptable.
inherits a logical flag. If FALSE, the specified environment is searched. Normally, only the current frame, the global frames, and databases are searched for an object.

If inherits=TRUE(the default), the parent frame of the current frame, its parent frame, and all further ancestors are searched.

ifnotfound a returned value if the given "x" object cannot be found the corresponding value. The default is NULL.

Details

To specify the environment in which to find the object, you can specify where as one of the following. If mode is provided but not set to the default value of "any", then only the specified type is sought.
get0 is an efficient way to combine exists and get in one call. If "x" does not exist in the specified environment with preferred mode, get0 returns the value of ifnotfound without an error. See the examples for the difference between get0 and get.
Value
existsreturns a logical value to indicate if the target object is found corresponding to the given name, mode, environment and other requirements.
get0checks the existence of the object and, if the object is found, returns the value of the object. If the object is not found, returns ifnotfound.
References
Becker, R. A., Chambers, J. M., and Wilks, A. R. 1988. The New S Language. Pacific Grove, CA: Wadsworth & Brooks/Cole Advanced Books and Software.
See Also
get
Examples

exists("CO2", where="package:stats") # [1] TRUE

exists("CO2", where=2) # [1] TRUE

if(exists("ls")) get("ls") else NULL get0("ls") # equivalent to above.

if(exists("foo_object")) get("foo_object") else NULL get0("foo_object") # equivalent to above.

get("foo_object") # with errors

Package base version 6.1.1-7
Package Index