Scoping &
Environments
Discover how R finds variables using lexical scoping and nested environments: the invisible architecture behind every R program.
What is an Environment?
An environment in R is a collection of name-value pairs: it maps variable names to their values. Think of it as a labelled box that holds all the variables you've created in a particular context.
Environments are Nested
Why Does Scoping Matter?
Scoping rules determine which value a variable name resolves to. Without clear scoping, a function might accidentally read or overwrite a variable from somewhere else in your code, causing silent, hard-to-find bugs.
The Lexical Scoping Rule
This is sometimes called static scoping because the lookup path is determined by the source code structure (the "lexical" structure), not by the runtime call stack.
How Lexical Scoping Works
R's Four Scoping Rules
Lexical vs Dynamic Scoping
| Lexical (R) | Dynamic | |
|---|---|---|
| Lookup based on | Where function is defined | Where function is called |
| Determined at | Write time (source structure) | Run time (call stack) |
| Predictability | High: read the code to know | Lower: depends on caller |
| Languages | R, Python, JavaScript, C | Bash, early Lisps, Emacs Lisp |
| Closures? | ✓ natural support | ✕ not meaningful |
Key Environment Types in R
The Search Path
How to Trace a Variable Lookup
Example 1: Name Masking
Example 2: Closures
Example 3: Dynamic Lookup
Useful Environment Functions
Common Mistakes
Question 1 of 5
Code:
x <- 1
f <- function() {
x <- 2
g <- function() x
g()
}
f()
What does \(f()\) return?
Question 2 of 5
In R, lexical scoping means a function looks up free variables in:
Question 3 of 5
Code:
make_counter <- function() {
count <- 0
function() {
count <<- count + 1
count
}
}
c1 <- make_counter()
c1(); c1(); c1()
What does the third call \(c1()\) return?
Question 4 of 5
Which R scoping rule explains why local variables do not persist between function calls?
Question 5 of 5
Code:
n <- 50
f <- function(x) x + n
g <- function() {
n <- 1000
f(10)
}
g()
What does \(g()\) return?