R Environments & Scope
When you use a name like x, R has to find out which x you mean. It looks in environments: collections of name → value bindings, each with a parent. Understanding them explains how functions see variables, why closures work and what <<- does.
The global environment
Variables you create at the top level of a script live in the global environment:
x <- 10
environment()
exists("x", envir = globalenv())
ls(globalenv())<environment: R_GlobalEnv>
[1] TRUE
[1] "x"
Function calls get their own environment
Each time a function runs, R creates a fresh environment for its arguments and local variables. It disappears when the function returns, and assignments inside it don't affect the caller:
x <- 10
change_x <- function() {
x <- 99 # a new local x
cat("inside:", x, "\n")
}
change_x()
cat("outside:", x, "\n")inside: 99
outside: 10
Lexical scoping
If a name isn't found locally, R looks in the environment where the function was defined (its enclosing environment), then that one's parent, and so on up to the global environment and the attached packages. This is called lexical scoping:
rate <- 0.2
tax <- function(amount) amount * rate # rate isn't local: found globally
tax(100)
rate <- 0.25
tax(100) # looked up at call time[1] 20
[1] 25
Relying on global variables like rate makes functions hard to reason about. Prefer passing values as arguments.
Closures
A function created inside another function keeps a reference to the environment it was created in. That's how a closure remembers values between calls:
make_counter <- function() {
count <- 0
function() {
count <<- count + 1 # modify count in the enclosing environment
count
}
}
next_id <- make_counter()
next_id()
next_id()
next_id()
other <- make_counter()
other()[1] 1
[1] 2
[1] 3
[1] 1
<<- assigns to the variable in the nearest enclosing environment that already has it (and creates a global one if none does). Each call to make_counter() creates a separate environment, so next_id and other count independently.
Working with environments directly
Environments are objects too. You can create them with new.env(), and use assign(), get() and $ to work with them. Unlike lists, environments are not copied when modified, which makes them useful as mutable state:
cache <- new.env()
assign("a", 1, envir = cache)
cache$b <- 2
sort(ls(cache))
get("b", envir = cache)
add_item <- function(env, key, value) env[[key]] <- value
add_item(cache, "c", 3)
mget(c("a", "c"), envir = cache)[1] "a" "b"
[1] 2
$a
[1] 1
$c
[1] 3
The function modified cache without returning it, because all names refer to the same environment.
The search path
When R can't find a name in your environments, it searches the attached packages. search() lists them in order:
search()
environmentName(environment(mean))[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
[1] "base"
If two packages define a function with the same name, the one attached later "masks" the other. Write pkg::fun() (e.g. stats::filter) to be explicit.
Dynamic lookup can surprise you
Because free variables are looked up when the function runs, a function can behave differently after you change a global variable, or fail if the variable disappears:
f <- function() y * 2
y <- 5
f()
rm(y)
f()[1] 10
Error in f() : object 'y' not found
Test yourself
After x <- 1; f <- function() { x <- 2 }; f(), what is x?
- 1
- 2
- NULL
- An error
What does <<- do?
- Compares two values
- Assigns in an enclosing environment
- Creates a constant
- Deletes a variable
Where does R look for a free variable used inside a function?
- Where the function is called from
- Where the function was defined, then its parents
- Only in the global environment
- Only in packages