Scoped environments

Scoped environments are named environments which form a parent-child hierarchy called the search path. They define what objects you can see (are in scope) from your workspace. They typically are package environments, i.e. special environments containing all exported functions from a package (and whose parent environment is the package namespace, which also contains unexported functions). Package environments are attached to the search path with base::library(). Note however that any environment can be attached to the search path, for example with the unrecommended base::attach() base function which transforms vectors to scoped environments.

  • You can list all scoped environments with scoped_names(). Unlike base::search(), it also mentions the empty environment that terminates the search path (it is given the name "NULL").

  • scoped_envs() returns all environments on the search path, including the empty environment.

  • pkg_env() takes a package name and returns the scoped environment of packages if they are attached to the search path, and throws an error otherwise.

  • is_scoped() allows you to check whether a named environment is on the search path.










The name of an environment attached to the search path. Call base::search() to see what is currently on the path.


The name of a package.

Search path

The search path is a chain of scoped environments where newly attached environments are the childs of earlier ones. However, the global environment, where everything you define at top-level ends up, is pinned as the head of that linked chain. Likewise, the base package environment is pinned as the tail of the chain. You can retrieve those environments with global_env() and base_env() respectively. The global environment is also the environment of the very first evaluation frame on the stack, see global_frame() and ctxt_stack().

Life cycle

These functions are experimental and may not belong to the rlang package. Expect API changes.

  • scoped_env
  • pkg_env
  • pkg_env_name
  • scoped_names
  • scoped_envs
  • is_scoped
  • base_env
  • global_env
library(rlang) # NOT RUN { # List the names of scoped environments: nms <- scoped_names() nms # The global environment is always the first in the chain: scoped_env(nms[[1]]) # And the scoped environment of the base package is always the last: scoped_env(nms[[length(nms)]]) # These two environments have their own shortcuts: global_env() base_env() # Packages appear in the search path with a special name. Use # pkg_env_name() to create that name: pkg_env_name("rlang") scoped_env(pkg_env_name("rlang")) # Alternatively, get the scoped environment of a package with # pkg_env(): pkg_env("utils") # }
Documentation reproduced from package rlang, version 0.2.0, License: GPL-3

Community examples

Looks like there are no examples yet.