ZetCode

R scoping and environments

last modified November 20, 2026

Every name in R lives in an environment, a table that maps names to values. The global environment holds the objects created at the console, each function call creates a new environment for its parameters and local variables, and every attached package contributes an environment of its own. Lexical scoping is the rule that decides which table a name is read from and where an assignment writes. This article looks at the objects themselves: globalenv, environment, new.env, parent.env, <<-, with, and the search path. The examples use R 4.5.2.

The global environment

An environment is a collection of bindings. globalenv() returns the global environment, the one that holds the objects created at top level. environment() returns the environment in which the call is evaluated; at top level it is the same global environment. Every environment has a parent, and parent.env returns it. The chain from the global environment through the attached packages ends at the empty environment, which has no bindings and no parent.

global-env.R
cat("global name:", environmentName(globalenv()), "\n")
cat("current name:", environmentName(environment()), "\n")
x <- 10
cat("objects:", paste(ls(), collapse = ", "), "\n")
env <- globalenv()
while (!identical(env, emptyenv())) {
  cat(" -", environmentName(env), "\n")
  env <- parent.env(env)
}

The script prints the name of the global environment twice, lists the object created so far, and then walks the parent chain. That chain is the search path: when a name is not found locally, R looks in each parent in order. The package environments appear in the order in which Rscript attached them. emptyenv() is the sentinel that stops the walk. It contains no bindings, and it has no parent.

$ Rscript global-env.R
global name: R_GlobalEnv 
current name: R_GlobalEnv 
objects: x 
 - R_GlobalEnv 
 - package:stats 
 - package:graphics 
 - package:grDevices 
 - package:utils 
 - package:datasets 
 - package:methods 
 - Autoloads 
 - base 

Function call environments

A call to a function creates a fresh environment for that call. The parameters and any variables assigned in the body live there. Its parent is the environment where the function was defined, not the environment of its caller. ls() with no arguments lists the bindings in the current environment, and exists(..., inherits = FALSE) checks only that environment without looking at its parents.

call-env.R
x <- 100
inspect <- function(a) {
  b <- a + 1
  cat("inside objects:", paste(ls(), collapse = ", "), "\n")
  cat("x from parent:", x, "\n")
  cat("x local:", exists("x", inherits = FALSE), "\n")
  b
}
result <- inspect(4)
cat("result:", result, "\n")
cat("global x:", x, "\n")

inspect(4) receives a = 4 and creates b = 5, so ls() shows only those two names. x is not local, so the lookup continues to the parent and finds 100. The final line confirms that the global x was only read, not changed. The call environment disappears when the call returns unless something keeps a reference to it; the closures article returns to that point.

$ Rscript call-env.R
inside objects: a, b 
x from parent: 100 
x local: FALSE 
result: 5 
global x: 100 

Lexical scope and shadowing

A nested function is defined inside another function, so its enclosing environment is the outer call's environment. The inner function reads x from that environment, not from the global environment. An assignment with <- creates a binding in the current environment, so it hides an outer binding of the same name instead of changing it. This rule is called lexical scoping because the parent comes from the nesting in the source code, not from who called the function.

shadow.R
x <- "global"
outer <- function() {
  x <- "outer"
  inner <- function() {
    cat("inner sees:", x, "\n")
  }
  inner()
  cat("outer sees:", x, "\n")
}
outer()
cat("global sees:", x, "\n")

inner is created during the call to outer and captures the environment of that call, where x is "outer". Both functions therefore print outer. The global x stays "global" because the assignment inside outer created a local binding rather than modifying the global one. Moving a function to another file does not change this: its enclosure is still the environment where it was defined.

$ Rscript shadow.R
inner sees: outer 
outer sees: outer 
global sees: global 

Creating environments with new.env

new.env() creates an independent table. The $ and [[ operators read and write bindings, while assign and get do the same with a name held in a variable. ls(envir = ...) lists the names. The parent argument sets the enclosing environment; emptyenv() makes the table self-contained, so a lookup cannot fall through to the global environment.

new-env.R
settings <- new.env(parent = emptyenv())
settings$theme <- "light"
settings$limit <- 25
assign("user", "anna", envir = settings)
cat("objects:", paste(ls(settings), collapse = ", "), "\n")
cat("theme:", settings$theme, "\n")
cat("user:", get("user", envir = settings), "\n")
cat("global has theme:", exists("theme", inherits = FALSE), "\n")

The settings environment contains three bindings: theme, limit, and user. The global environment does not have a theme, even though the value is easy to read through settings$theme. new.env() defaults to the calling environment as its parent, so pass parent = emptyenv() when the table should not see anything else. Passing an environment to a function does not copy its contents, which is what makes it useful as a shared store.

$ Rscript new-env.R
objects: limit, theme, user 
theme: light 
user: anna 
global has theme: FALSE 

Superassignment

<- always assigns in the current environment. <<- does not create a local binding: it walks the parent chain until it finds an existing binding and updates that one. If no binding exists, it assigns in the global environment. The next script uses <<- to change a variable in the environment of the enclosing function.

superassign.R
outer <- function() {
  value <- 10
  change <- function() {
    value <<- value + 5
    value
  }
  cat("change returns:", change(), "\n")
  cat("outer value:", value, "\n")
}
outer()
cat("global value exists:", exists("value", inherits = FALSE), "\n")

change is defined inside outer, so its parent is the call environment of outer, where value is 10. The statement value <<- value + 5 updates that binding. The final check confirms that no global value was created. <<- is easy to misuse because the assignment can reach far up the chain; the closures article uses it deliberately to keep state.

$ Rscript superassign.R
change returns: 15 
outer value: 15 
global value exists: FALSE 

Evaluating in a list or environment

with evaluates an expression using a list or an environment as the enclosing scope. It is a compact way to avoid repeating a data frame name. within does the same for reading and returns a modified copy of the object, so the original stays unchanged. Both functions evaluate in a temporary environment whose parent is the caller.

with-env.R
sale <- list(item = "lamp", price = 40, quantity = 3)
total <- with(sale, price * quantity)
cat("total:", total, "\n")
sale2 <- within(sale, {
  total <- price * quantity
  price <- price * 0.9
})
cat("discounted total:", sale2$total, "\n")
cat("original price:", sale$price, "\n")
cat("new price:", sale2$price, "\n")

with(sale, price * quantity) finds both names in the list and returns 120. within evaluates its two assignments in order: total is computed from the original price, then the price is reduced by ten percent. The returned list has both changes; the original sale still has price 40. This makes within useful for a quick transformation, while with is enough when only a value is needed.

$ Rscript with-env.R
total: 120 
discounted total: 120 
original price: 40 
new price: 36 

Attaching and detaching

attach puts a list or data frame on the search path, which makes its names available without a prefix. detach removes it. Attaching is convenient in an interactive session, but it changes the meaning of every subsequent lookup: a name in the attached list can mask a function or a variable from another package. Code that depends on the search path is hard to read and easy to break.

search-path.R
values <- list(alpha = 1, beta = 2)
attach(values)
cat("alpha:", alpha, "\n")
cat("on search path:", "values" %in% search(), "\n")
detach("values")
cat("still attached:", "values" %in% search(), "\n")

attach(values) creates an environment named values on the search path, so alpha resolves to 1. detach("values") removes the entry, and the final check is false. with(values, alpha) gives the same convenience for one expression without changing the search path, which is why most code prefers it. A package that attaches a data set should at least document the names it adds.

$ Rscript search-path.R
alpha: 1 
on search path: TRUE 
still attached: FALSE 

A complete example: shared state

Environments have reference semantics: passing one to a function does not copy it. A function can therefore update a shared table in place, and every other function that holds the same environment sees the change. Lists do not behave this way; a list is copied when a function modifies it. The final example uses an environment as a small session store and contrasts it with a list.

shared-state.R
session <- new.env(parent = emptyenv())
session$user <- "anna"
session$visits <- 0
session$pages <- character(0)
record <- function(page) {
  session$visits <- session$visits + 1
  session$pages <- c(session$pages, page)
  paste(session$visits, session$user, page)
}
cat(record("home"), "\n")
cat(record("prices"), "\n")
cat(record("contact"), "\n")
cat("visits:", session$visits, "\n")
cat("pages:", paste(session$pages, collapse = " -> "), "\n")
plain <- list(visits = 0)
bump <- function() {
  plain$visits <- plain$visits + 1
  plain$visits
}
cat("bump returns:", bump(), "\n")
cat("list visits:", plain$visits, "\n")

record updates session$visits and session$pages inside the environment; no <<- is needed because the environment object itself is modified in place. Three calls leave three visits and three pages. bump modifies its local copy of the list plain, so the global list still has zero visits. This difference is the reason environments are used for registries, caches, and mutable objects.

$ Rscript shared-state.R
1 anna home 
2 anna prices 
3 anna contact 
visits: 3 
pages: home -> prices -> contact 
bump returns: 1 
list visits: 0 

Next steps

The closures article builds on this material: a function returned from another function keeps a reference to the environment where it was created, which is how it remembers state. The functions article covers the basics of arguments and lexical lookup, the debugging article shows how sys.frames exposes call environments, and the R6 article uses environments to implement mutable objects with reference semantics.

Source

R manual: environments

R manual: assign and get

R manual: with and within

R manual: attach and detach

Advanced R: Environments

In this article we treated environments as the tables behind R names. We walked the search path from the global environment to emptyenv, saw a new call environment created for each function call, and used lexical scope and shadowing to predict which binding a name would find. new.env made independent stores, <<- updated a binding in a parent, and with, within, attach, and detach evaluated or changed the search path. The final example showed the reference semantics that distinguish an environment from a list. The closures article takes the next step and returns functions that keep these environments alive.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.