Environment (R)

An environment is R's structure for binding names to values — essentially a lookup table of variables. Every function call creates one, and they form the chain R searches to resolve a variable.

R

An environment maps variable names to values and has a parent environment. When you reference a name, R searches the current environment, then its parent, then up the chain to the global environment and loaded packages, until it finds a binding. This search chain is what makes scoping work.

R uses lexical (static) scoping: a function's parent is the environment where the function was defined, not where it's called. That's what lets closures capture and remember variables from their defining scope. The global environment (.GlobalEnv) is your interactive workspace; each function call gets a fresh local environment.

Unlike most R objects, environments have reference semantics — they aren't copied when passed around, so modifying one in place affects all references. This makes them occasionally useful for mutable state, though most R code favors copy-on-modify values. ls() and environment() let you inspect them.

Syntax

f <- function() { x <- 1; environment() }
ls(envir = globalenv())

Examples

R

make_counter <- function() {
  count <- 0
  function() {
    count <<- count + 1
    count
  }
}
counter <- make_counter()
print(counter())
print(counter())

Output:

[1] 1
[1] 2

See also

Back to the Dictionary