# Get the environment of frame objects. If no argument is supplied,
# the current frame is used:
fn <- function() {
list(
env(call_frame()),
env()
)
}
fn()
# Environment of closure functions:
env(fn)
# There is also an assignment operator:
env(fn) <- base_env()
env(fn)
# new_env() creates by default an environment whose parent is the
# empty environment. Here we return a new environment that has
# the evaluation environment (or frame environment) of a function
# as parent:
fn <- function() {
my_object <- "A"
new_env(env())
}
frame_env <- fn()
# The new environment is empty:
env_has(frame_env, "my_object")
# But sees objects defined inside fn() by inheriting from its
# parent:
env_has(frame_env, "my_object", inherit = TRUE)
# Create a new environment with a particular scope by setting a
# parent. When inheriting from the empty environment (the default),
# the environment will have no object in scope at all:
env <- new_env()
env_has(env, "lapply", inherit = TRUE)
# The base package environment is often a good default choice for a
# parent environment because it contains all standard base
# functions. Also note that it will never inherit from other loaded
# package environments since R keeps the base package at the tail
# of the search path:
env <- new_env(base_env())
env_has(env, "lapply", inherit = TRUE)
# Note that all other package environments inherit from base_env()
# as well:
env <- new_env(pkg_env("rlang"))
env_has(env, "env_has", inherit = TRUE)
env_has(env, "lapply", inherit = TRUE)
# The parent argument of new_env() is passed to as_env() to provide
# handy shortcuts:
env <- new_env("rlang")
identical(env_parent(env), pkg_env("rlang"))
# Get the parent environment with env_parent():
env_parent(global_env())
# Or the tail environment with env_tail():
env_tail(global_env())
# By default, env_parent() returns the parent environment of the
# current evaluation frame. If called at top-level (the global
# frame), the following two expressions are equivalent:
env_parent()
env_parent(global_env())
# This default is more handy when called within a function. In this
# case, the enclosure environment of the function is returned
# (since it is the parent of the evaluation frame):
enclos_env <- new_env(pkg_env("rlang"))
fn <- with_env(enclos_env, function() env_parent())
identical(enclos_env, fn())
Run the code above in your browser using DataLab