6.6 Environments

R RUNTIMESTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18

6.6.1 Motivation

Every name lookup in R is a search through environments. When you type x at the prompt, R searches environments until it finds a binding for x. When you call a function, R creates an environment to hold the arguments. When you attach a package, R inserts an environment into the search path. The environment is the data structure behind scoping, namespaces, and the workspace. See how R executes code for where this sits in the evaluator.

Environments are also the main exception to value semantics that R code meets. Almost every R object behaves as a value with copy-on-modify rules. Environments are references instead, as external pointers are. Two variables can point at the same environment, and a write through one is visible through the other. That reference behavior powers closures, reference classes, and R6. It is also one of the hardest problems for any plan to run R on multiple threads.

6.6.2 Mental model

An environment is two things. The first is a frame: a set of bindings from names to values. The second is a pointer to a parent environment.

Think of a stack of dictionaries, each with a fallback pointer to the next. A lookup that misses in one dictionary falls through to the next. In R, the fallback pointer is the parent, and the walk up the chain implements lexical scoping.

Lexical scoping means the definition site of a function decides which names it sees. The call site does not. Every function remembers the environment where it was defined. Every call creates a fresh frame whose parent is that remembered environment. Lookup starts in the fresh frame and walks parents from there. So the walk retraces the nesting of the source code, not the call stack.

6.6.3 Mechanism

Lookup walks the parent chain

To evaluate the symbol x, R searches the current frame. If the frame has no binding for x, R moves to the parent and searches again. The walk continues until a binding appears or the chain ends. The chain ends at the empty environment, the one environment with no parent. If the walk reaches it, R signals object 'x' not found.

You can run the same walk by hand. exists("x") reports whether the walk finds a binding. exists("x", inherits = FALSE) checks only the current frame and skips the walk. get() and get0() accept the same inherits switch. Function lookup adds one refinement. When a symbol appears in call position, as in x(1), the walk skips bindings whose value is not a function. That rule is why c <- 1 does not break every later call to c().

The fixed landmarks

A handful of environments have names and fixed roles:

  • globalenv() is the user workspace. Top-level assignments at the prompt land here.
  • baseenv() holds the base package. sum, c, and if live behind it.
  • emptyenv() is the end of every chain. It has no frame and no parent.
  • The search path is the chain from the global environment down to base. library() inserts an attached package environment directly under the global environment. search() prints the current chain.
  • Package namespaces are environments too. A namespace holds the internal definitions of a package. Its parent is an imports environment, which holds only what the package imported. The parent of the imports environment is the base namespace.

A fresh session shows the search path directly:

search()
#  [1] ".GlobalEnv"        "package:stats"     "package:graphics"
#  [4] "package:grDevices" "package:utils"     "package:datasets"
#  [7] "package:methods"   "Autoloads"         "package:base"

Each entry is one environment, and each is the parent of the entry to its left. A top-level lookup that misses in your workspace tries package:stats next, then the rest in order.

The namespace design gives package code a sealed view of the world. A function inside the stats package finds var in its own namespace. It finds imported functions in the imports environment. It does not see your workspace until the chain passes through the global environment.

Function calls create frames

Each function call creates one fresh environment, the evaluation frame for that call. The frame binds the parameter names to promises, and local assignments add more bindings. The parent of the frame is the environment where the function was defined, not the environment of the caller. environment(fn) returns that defining environment for a closure fn. For a package function it returns the package namespace.

The full lookup chain for a call to a package function looks like this:

flowchart TD
  frame["evaluation frame<br/>of the call"] --> ns["namespace:stats"]
  ns --> imports["imports:stats"]
  imports --> basens["namespace:base"]
  basens --> global["global environment"]
  global --> attached["attached packages"]
  attached --> base["package:base"]
  base --> empty["empty environment"]

Lookup from inside a stats function walks this chain top to bottom and stops at the first binding it finds.

The top link changes on every call. The namespace and its imports environment are built when the namespace loads and then locked. The base namespace is built and locked once, at startup. From the global environment down, the chain is the search path, which changes whenever a package is attached or detached.

parent.frame() is not parent.env()

These two functions confuse almost everyone, because both contain the word parent. They answer different questions.

parent.env(e) answers a static question: which environment does lookup try after e? It reads the parent pointer. The answer depends only on where things were defined.

parent.frame() answers a dynamic question: which evaluation frame called me? It inspects the call stack. The answer depends on who called whom at run time.

One example shows the difference:

x <- "global"
f <- function() {
  x <- "from f"
  g()
}
g <- function() x
f()   # "global"

g was defined at top level, so its chain goes straight to the global environment. The frame of f is not on that chain. The binding x <- "from f" is invisible to g, even though f is the caller.

parent.frame() reaches what lexical lookup cannot:

h <- function() {
  caller <- parent.frame()
  get("x", envir = caller)
}
f2 <- function() {
  x <- "from f2"
  h()
}
f2()  # "from f2"

Here h asks for the frame of its caller and reads x from it directly. eval() uses parent.frame() as its default environment, and most non-standard evaluation tricks are built on this move. Use it with care. Code that reads the caller’s frame breaks the sealed-view guarantee that namespaces work hard to provide.

6.6.4 A simple example

Reference semantics, demonstrated

R vectors copy on modification. A function that modifies a vector argument modifies a private copy:

touch_vector <- function(v) {
  v[1] <- 99
  invisible(NULL)
}
x <- c(1, 2, 3)
touch_vector(x)
x[1]    # 1: the function changed a private copy

An environment passed the same way behaves in the opposite way:

touch_env <- function(e) {
  e$n <- 99
  invisible(NULL)
}
env <- new.env()
env$n <- 1
touch_env(env)
env$n   # 99: the function wrote into the one shared environment

No copy happened. e inside the function and env outside are the same object. That is reference semantics, and among the types R code handles every day, environments are the one that has it.

Three familiar tools are thin wrappers over this behavior. local() runs a block inside a fresh environment and returns the last value. assign("n", 10, envir = e) writes a binding into a chosen environment. The superassignment operator <<- walks the parent chain, and it rebinds the first existing binding it finds. If no binding exists anywhere on the chain, <<- creates one in the global environment. That fallback is a common source of bugs.

Two closures, one environment

A closure is a function plus a captured environment. Two closures defined in the same frame capture the same frame. That gives them shared private state:

make_counter <- function() {
  n <- 0
  inc <- function() {
    n <<- n + 1
    n
  }
  get <- function() n
  list(inc = inc, get = get)
}

counter <- make_counter()
counter$inc()   # 1
counter$inc()   # 2
counter$get()   # 2

flowchart TD
  inc["closure: inc"] --> shared["captured frame of<br/>make_counter: n = 2"]
  get["closure: get"] --> shared
  shared --> global["global environment"]

Both closures point at one captured frame, so a write through inc is visible through get.

The frame of the make_counter call outlives the call, because two closures still point at it. inc writes n through <<-, and get reads the same binding. Every object system built on closures, from local() idioms to R6, is this diagram with more bindings.

6.6.5 Internal mechanics

At the C level an environment is a SEXP of type ENVSXP. It carries three pointers: the frame, the enclosure (the parent), and an optional hash table.

In an unhashed environment the frame is a linked list of bindings, one cons cell per binding, and lookup is a linear scan. Function evaluation frames use this form because most calls bind only a handful of names, and a short list beats a hash table at that size. The cells are cheap to allocate and die young, which suits the generational collector.

Environments expected to hold many bindings use the hash table pointer instead. new.env() creates a hashed environment by default, and the global environment and package namespaces are hashed. A hashed frame gives near constant time lookup no matter how many bindings it holds. A large unhashed frame degrades to a linear scan on every miss, and misses are the common case during a chain walk.

The base environment is a special case. Its bindings do not live in a frame at all. Each symbol in R’s symbol table has a value slot, SYMVALUE, and base bindings live directly in those slots. A lookup that reaches base reads one field of the symbol it already holds. “R Internals” describes this arrangement in its section on environments and variable lookup: the base environment’s frame is not used, and its bindings are the symbols in the global symbol table whose values are set.

The cost of lookup

Symbol lookup is one of the hottest operations in the interpreter. The whole mechanism fits in a few lines of pseudocode:

lookup(symbol, env):
  while env is not the empty environment:
    if env is the base environment:
      return SYMVALUE(symbol) if it is set
    binding = search frame of env for symbol   # scan or hash probe
    if binding exists:
      return value of binding
    env = parent(env)
  error "object not found"

The interpreter runs this loop for nearly every symbol it evaluates. Three factors set its cost:

  • Chain depth. Every environment between the current frame and the binding adds a scan. Code defined at top level that leans on base functions walks the whole search path per symbol.
  • Frame size. An unhashed frame with hundreds of bindings turns each of those scans into hundreds of pointer chases.
  • Search path length. Every attached package is one more environment between the global environment and base.

R blunts the third factor with a global cache. Bindings found through the search path are recorded in one hashed cache, so repeated lookups skip the package-by-package walk. The cache covers the global environment, the base environment, and attached environments. Attaching or detaching an environment flushes its symbols from the cache, and defining or removing a binding in one of those environments flushes that symbol. The cache is why library() calls do not make every subsequent lookup slower in proportion.

Two more mechanics matter for later pages. First, lockEnvironment() and lockBinding() can freeze an environment or a single binding. R locks package namespaces after load, which is why you cannot assign into namespace:stats. Second, environments are ordinary heap objects under the garbage collector. A captured frame keeps every binding in it reachable. A closure that captures a frame with a large data frame in it keeps that data frame alive, whether the closure uses it or not, which makes it a classic R memory leak.

6.6.6 The hard part

Everything above assumes one thread of execution. Break that assumption and environments become a central problem.

A vector can cross a thread boundary by copy, and the copy is safe because nobody can observe the difference. An environment cannot, because its identity is its meaning: a copied counter environment is a different counter. So threads that want to cooperate through an environment must share the one object, and the one object is mutable through every reference. Two threads that write bindings concurrently produce a data race on the frame structure itself.

Shared mutable environments are among the hardest R objects to share across threads. Vectors can cross by copy. Environments must alias to keep their meaning, and every alias can write.

The problem is wider than user code with new.env(). The global environment is a shared mutable environment that every top-level assignment writes. Package namespaces are environments whose lazy-loaded bindings are promises, and the first use of each one writes its value into that promise. Forcing an argument promise in an evaluation frame is a write in the same way. Even code that looks read-only writes constantly into objects that environments hold. Any design for shared memory between R threads must answer for all of these writers, not just the visible ones.

6.6.7 Relevance to my work

threaded-r runs multiple isolated interpreters in one process, one owner thread each. That model collides with the base environment trick described above. Upstream R stores base bindings in SYMVALUE slots on the symbol table, and the symbol table is one shared structure. If two interpreters share those slots, one interpreter’s write to a base binding is visible in the other. The fork therefore gives each interpreter its own symbol table, so most base bindings stay in the SYMVALUE slots of that interpreter’s own symbols. The exception is 38 symbols, such as R_NamesSymbol, that compiled packages reach through exported globals. Those stay one object each, shared by every interpreter, and each interpreter keeps their bindings in a small record of its own.

threaded-r first measured the cost of a hash probe on a base lookup, using an identical closure in an attached hashed environment as a stand-in for a hashed base environment. It cost 1.3 to 1.9 percent on a single-threaded microbenchmark built as the worst case, one hash probe on every base lookup where upstream R reads one field of the symbol. The fork then chose the smaller design above: the other base symbols keep the one-field SYMVALUE lookup, and only the 38 shared symbols go through the per-interpreter record.

r-in-rust never had the problem, because it never had the shared state. Each interpreter owns its heap, its symbol table, and every environment in it. Environments are ordinary objects on the interpreter’s own heap, under its own GC, and a gate check that runs before every commit keeps the interpreter crates free of global mutable state, with a short reviewed allowlist for the C API crates. The cost moved elsewhere: nothing is shared, so nothing crosses between interpreters without an explicit step.

sunlight meets environments at the worker boundary. Workers are forked from a prewarmed template process, so each worker starts with a copy of every loaded namespace at fork time. After that point the copies diverge. A task is a closure, and a closure drags its captured environment with it, together with everything reachable from that environment. sunlight therefore treats capture as an interface: what a task closure captures must be explicit. sunlight checks the capture set at spawn, before the task crosses to a worker. This bounds serialization cost and stops a task from silently depending on state that exists only in the parent.

6.6.8 Open questions

A locked namespace looks immutable, which suggests interpreters can share it read-only. But lazy loading, method tables, and GC bookkeeping all write into or around namespace objects after the lock.

Can multiple interpreters share package namespace environments read-only, with private copies only for the frames that mutate?

The page shared environments is the home for this question and tracks the candidate designs.

Further reading

Where this appears

  • threaded-r Base bindings live in symbol slots, so the fork gives each interpreter its own symbol table and keeps the bindings of 38 shared symbols in a per-interpreter record.
  • r-in-rust (rrs) The Rust interpreter must reproduce frame plus parent lookup with no shared mutable state.
  • sunlight Closures capture environments, so the worker boundary must decide what crosses at spawn.

Where to go next

Back to top