Get, set, test for and create environments.
environment(fun = NULL) environment(fun) <- value is.environment(obj) .GlobalEnv globalenv() .BaseNamespaceEnv emptyenv() baseenv() new.env(hash = FALSE, parent = parent.frame()) parent.env(env) parent.env(env) <- value
NULL, which is the default. |
|an environment to associate with the function|
|an arbitrary object.|
|a logical, if
environment created. |
Environments consist of a frame, or collection of named objects, and a pointer to an enclosing environment. The most common example is the frame of variables local to a function call; its enclosure is the environment where the function was defined. The enclosing environment is distinguished from the parent frame: the latter (returned by
parent.frame) refers to the environment of the caller of a function.
The global environment
.GlobalEnv, more often known as the user’s workspace, is the first item on the search path. It can also be accessed by
globalenv(). On the search path, each item’s enclosure is the next item.
.BaseNamespaceEnv is the namespace environment for the base package. The environment of the base package itself is available as
baseenv(). The ultimate enclosure of any environment is the empty environment
emptyenv(), to which nothing may be assigned. If one follows the
parent.env() chain of enclosures back far enough from any environment, eventually one reaches the empty environment.
The replacement function
parent.env<- is extremely dangerous as it can be used to destructively change environments in ways that violate assumptions made by the internal C code. It may be removed in the near future.
is.environment is generic: you can write methods to handle specific classes of objects, see InternalMethods.
fun is a function or a formula then
environment(fun) returns the environment associated with that function or formula. If
NULL then the current evaluation environment is returned.
The replacement form sets the environment of the function or formula
fun to the
obj is an
new.env returns a new (empty) environment enclosed in the parent’s environment, by default.
parent.env returns the parent environment of its argument.
parent.env<- sets the enclosing environment of its first argument.
f <- function() "top level function" ##-- all three give the same: environment() environment(f) .GlobalEnv ls(envir=environment(approxfun(1:2,1:2, method="const"))) is.environment(.GlobalEnv) # TRUE e1 <- new.env(parent = baseenv()) # this one has enclosure package:base. e2 <- new.env(parent = e1) assign("a", 3, env=e1) ls(e1) ls(e2) exists("a", env=e2) # this succeeds by inheritance exists("a", env=e2, inherits = FALSE) exists("+", env=e2) # this succeeds by inheritance