01 / 21

Scoping &
Environments

Discover how R finds variables using lexical scoping and nested environments: the invisible architecture behind every R program.

R Programming

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.

Names
Character strings like \(x\), \(my\_data\), or \(result\) that identify stored values.
Values
Any R object: numbers, vectors, functions, data frames, or even other environments.
Parent
Every environment (except the empty env) has a parent, forming a chain R walks when searching for names.

Environments are Nested

Global Environment
\(x \leftarrow 10\)
\(y \leftarrow 20\)
outer() environment
\(a \leftarrow 5\)
inner() environment
\(b \leftarrow 3\)
uses: \(a, x, b\)
parent parent

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.

1
Predictability: you know exactly where each variable lives and which copy a function sees.
2
Encapsulation: functions can have local variables without polluting the global space.
3
Closures: functions can "remember" the environment they were created in, enabling powerful patterns like function factories.

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.

Defined (Lexical)
R searches the environment where the function's code was written.
Called (Dynamic)
Some languages search the environment where the function is invoked. R does not do this.

How Lexical Scoping Works

Definition Site
\(n \leftarrow 100\)
\(f \leftarrow \text{function}(x) \{ \)
\(x + n\)
\}\)
\(n\) is a "free variable" in \(f\)
✓ R finds \(n = 100\) here
Call Site
\(n \leftarrow 999\)
\(f(5)\) # returns 105
✕ R ignores \(n = 999\)
(dynamic scoping would use it)
looks up n

R's Four Scoping Rules

1
Name Masking: names defined inside a function mask names in the parent environment.
2
Functions vs. Variables: R uses separate search logic when looking for a name being used as a function (it skips non-function objects).
3
Fresh Start: every time a function is called, a brand-new environment is created. Previous calls don't leave behind state.
4
Dynamic Lookup: R looks up free variable values when the function runs, not when it is defined. So the value can change between calls.

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

Global Env
Your interactive workspace. Variables you create at the console live here. Access with \(globalenv()\).
Package Envs
Each loaded package has its own environment on the search path. Check with \(search()\).
Function Envs
Created fresh on every function call. Contains local variables and arguments. Discarded when the call returns.

The Search Path

Global package: ggplot2 package: stats base empty env ... R searches left → right along this chain f() local env parent

How to Trace a Variable Lookup

1
Identify the free variable: find a name used inside a function that is not a parameter or locally assigned.
2
Find the enclosing environment: look at where the function was defined in the source code (not where it is called).
3
Check that environment: is the name defined there? If yes, that's the value R will use.
4
Walk up the chain: if not found, move to the parent environment and repeat. Continue until the empty environment (which throws an error).
5
Remember dynamic lookup: the value is retrieved at run time, so if the binding changes between calls, the function sees the new value.

Example 1: Name Masking

x <- 10 f <- function() { x <- 20 # local x masks global x x } f() # returns 20 x # still 10 in global
Global
\(x = 10\)
f() local
\(x = 20\) (masks!)
parent
✓ \(f()\) finds \(x = 20\) locally
No need to check parent Global x is unchanged: still 10

Example 2: Closures

make_adder <- function(n) { function(x) x + n } add5 <- make_adder(5) add10 <- make_adder(10) add5(3) # 8 add10(3) # 13

Example 3: Dynamic Lookup

multiplier <- 2 scale <- function(x) { x * multiplier # free variable } scale(5) # 10 multiplier <- 100 scale(5) # 500 (not 10!)

Useful Environment Functions

\(environment(f)\)
Returns the enclosing environment of function \(f\): where it looks up free variables.
\(ls(envir)\)
Lists all names bound in the given environment.
\(parent.env(e)\)
Returns the parent of environment \(e\), letting you walk the chain.
environment(scale) # <environment: R_GlobalEnv> ls(environment(add5)) # [1] "n" get("n", envir = environment(add5)) # [1] 5

Common Mistakes

✕ Confusing Definition vs Call Site
Assuming a function uses the caller's variables. R uses the definition site, not the call site.
✕ Forgetting Fresh Start
Expecting local variables to persist between function calls. Each call creates a brand-new environment.
✕ Relying on Global Variables
Using free variables carelessly. If the global value changes, your function silently changes behavior (dynamic lookup).

Question 1 of 5

What does \(f()\) return?

Question 2 of 5

In R, lexical scoping means a function looks up free variables in:

Question 3 of 5

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

What does \(g()\) return?