0Pricing
R Academy · Lesson

Lexical Scoping Rules

Understand how R finds variables by searching parent environments.

What is Lexical Scoping?

Lexical scoping means a function looks up variables where it was defined, not where it is called. R uses lexical scoping. This is predictable: the environment a function searches is fixed at creation time, not at call time.

x <- 'global'
f <- function() {
  cat('x =', x, '\n')  # looks where f was defined (global)
}
local({
  x <- 'local to local block'
  f()  # still prints global x, not the local one
})

Lexical vs Dynamic Scoping

In dynamic scoping (used in some other languages), a function would find the variable in the calling environment. R uses lexical scoping instead: the enclosing environment at definition time always wins. This makes functions behave consistently regardless of where they are called from.

val <- 100
make_adder <- function(n) {
  # n is captured from the definition environment
  function(x) x + n
}
add10 <- make_adder(10)
add20 <- make_adder(20)
cat(add10(5), '\n')   # 15 — n=10 from definition
cat(add20(5), '\n')   # 25 — n=20 from definition

All lessons in this course

  1. What Is an Environment in R?
  2. Lexical Scoping Rules
  3. Global vs Local Scope
  4. Creating and Inspecting Environments
← Back to R Academy