ZetCode

R closures

last modified November 20, 2026

A closure is a function together with the environment in which it was created. R builds closures automatically: every function value carries a reference to its enclosing environment, and when the function is called, that environment becomes the parent of the new call environment. The consequence is that a function can return another function that remembers values from the call that created it. This article builds closures for partial application, counters, memoization, and stateful objects. The examples use R 4.5.2.

A function that returns a function

make_multiplier takes a factor and returns a new function. The returned function has one parameter, x, and uses factor from the call that created it. make_multiplier(2) and make_multiplier(3) create two closures with separate environments, even though they run the same function body.

multiplier.R
make_multiplier <- function(factor) {
  function(x) x * factor
}
double <- make_multiplier(2)
triple <- make_multiplier(3)
cat("double 5:", double(5), "\n")
cat("triple 5:", triple(5), "\n")
cat("factor of triple:", environment(triple)$factor, "\n")

double multiplies by two and triple by three. environment(triple) is the call environment of make_multiplier(3), which still exists because the closure refers to it; $factor reads the captured binding. The function body is shared, the environment is not. This is the mechanism behind every example in the rest of the article.

$ Rscript multiplier.R
double 5: 10 
triple 5: 15 
factor of triple: 3 

State kept between calls

The captured environment is not read-only. <<- finds count in the parent environment and updates it, so each call to the returned function changes the same binding. The initial value becomes part of the closure. Two counters made by separate calls do not share state.

counter.R
make_counter <- function(start = 0) {
  count <- start
  increment <- function(step = 1) {
    count <<- count + step
    count
  }
  increment
}
first <- make_counter()
second <- make_counter(100)
cat("first:", first(), first(), first(2), "\n")
cat("second:", second(), "\n")
cat("first again:", first(), "\n")

first starts at zero and adds one, one, then two; the printed values are 1, 2, and 4. second starts at 100 and has its own count, so it prints 101. The next call to first continues from 4 and prints 5. The environment is the memory of the closure, and the function is the only way to reach it.

$ Rscript counter.R
first: 1 2 4 
second: 101 
first again: 5 

The captured environment

A closure keeps its environment alive after the factory returns. The environment is an ordinary object with a parent, and it is garbage-collected only when no function refers to it. environment(f) returns it, and get or $ reads a binding from it. The next example makes two loggers with different prefixes.

capture.R
make_logger <- function(prefix) {
  function(message) paste0("[", prefix, "] ", message)
}
info <- make_logger("INFO")
warn <- make_logger("WARN")
cat(info("started"), "\n")
cat(warn("low disk"), "\n")
cat("prefix stored:", exists("prefix", envir = environment(info), inherits = FALSE), "\n")
cat("prefix value:", get("prefix", envir = environment(info)), "\n")

info and warn share the same function body but not the same prefix. Each call to make_logger creates a new environment with a prefix binding. exists with inherits = FALSE checks that environment directly, and get reads the value. The prefix survives because the returned function is a closure over it, not because the prefix is stored in a global variable.

$ Rscript capture.R
[INFO] started 
[WARN] low disk 
prefix stored: TRUE 
prefix value: INFO 

The loop variable trap

A closure captures a binding, not the value the binding had at the moment the function was created. In a for loop, all iterations share one binding for the loop variable, so functions created in the loop all see the final value. The fix is to create a new environment for each value, usually by calling a factory function inside the loop.

loop-trap.R
fns <- list()
for (i in 1:3) {
  fns[[i]] <- function() i
}
cat("shared binding:", fns[[1]](), fns[[2]](), fns[[3]](), "\n")
make_getter <- function(value) {
  force(value)
  function() value
}
fns2 <- list()
for (i in 1:3) {
  fns2[[i]] <- make_getter(i)
}
cat("captured value:", fns2[[1]](), fns2[[2]](), fns2[[3]](), "\n")

The first list holds three functions that all read the global i, which is 3 after the loop. The second list calls make_getter(i) in every iteration. Each call creates a new environment with its own value binding, so the three functions return 1, 2, and 3. force(value) evaluates the argument before the closure is created; without it, value would be a promise that still points at the loop variable.

$ Rscript loop-trap.R
shared binding: 3 3 3 
captured value: 1 2 3 

Memoization

A cache is a natural use for a closure. make_memo creates a private environment and returns a function that checks the cache before calling the original function. The cache is not visible from the global environment, and each memoized function gets its own cache. exists and assign work on the environment directly.

memo.R
make_memo <- function(f) {
  cache <- new.env(parent = emptyenv())
  function(x) {
    key <- as.character(x)
    if (exists(key, envir = cache, inherits = FALSE)) {
      return(get(key, envir = cache))
    }
    value <- f(x)
    assign(key, value, envir = cache)
    value
  }
}
calls <- 0
square <- function(x) {
  calls <<- calls + 1
  x * x
}
memo_square <- make_memo(square)
cat(memo_square(4), memo_square(4), memo_square(5), "\n")
cat("calls:", calls, "\n")
cat("cached keys:", paste(ls(environment(memo_square)$cache), collapse = ", "), "\n")

The first call with 4 computes 16 and stores it under the key "4". The second call returns the stored value without calling square, and the call with 5 computes and stores 25. calls is 2, not 3. ls(environment(memo_square)$cache) shows the two keys. The cache survives between calls because the returned function refers to its environment, and it stays private because no other function has a reference to that environment.

$ Rscript memo.R
16 16 25 
calls: 2 
cached keys: 4, 5 

A complete example: a bank account

A closure can hold several functions over one environment. The account below keeps balance private and exposes deposit, withdraw, and a balance reader. The functions share the same balance binding, so a deposit is visible to a later withdrawal. Error handling keeps the balance unchanged when a withdrawal is too large.

account.R
make_account <- function(balance = 0) {
  deposit <- function(amount) {
    if (amount <= 0) stop("amount must be positive", call. = FALSE)
    balance <<- balance + amount
    balance
  }
  withdraw <- function(amount) {
    if (amount > balance) stop("insufficient funds", call. = FALSE)
    balance <<- balance - amount
    balance
  }
  list(
    deposit = deposit,
    withdraw = withdraw,
    balance = function() balance
  )
}
savings <- make_account(100)
cat("deposit:", savings$deposit(50), "\n")
cat("withdraw:", savings$withdraw(30), "\n")
cat("balance:", savings$balance(), "\n")
other <- make_account()
cat("other balance:", other$balance(), "\n")
failure <- tryCatch(savings$withdraw(500), error = function(e) conditionMessage(e))
cat("failed:", failure, "\n")
cat("balance after failure:", savings$balance(), "\n")

The account starts at 100, receives 50, and pays out 30, leaving 120. A second account starts at zero and is independent. The attempted withdrawal of 500 signals an error before the assignment, so the balance stays 120; tryCatch turns the condition into the message that is printed. The balance cannot be changed except through the returned functions, which is the closure equivalent of a private field.

$ Rscript account.R
deposit: 150 
withdraw: 120 
balance: 120 
other balance: 0 
failed: insufficient funds 
balance after failure: 120 

Next steps

The recursion article uses functions that call themselves, and the performance article shows how closures and Rprof interact when a function is called many times. The environments article explains the parent chain that <<- walks, the functions article covers arguments and lazy evaluation, and the R6 article builds the same kind of mutable object with reference classes.

Source

Advanced R: Function factories

Advanced R: Closures

R manual: function

R manual: environments

R manual: force

In this article a function returned another function, and the returned function kept the environment of the call that created it. That environment gave each closure a private factor, count, or cache. We used <<- to update a captured binding, avoided the loop variable trap with a factory and force, and built a memoized function and a small bank account. The environments article explains the lookup rules behind these examples in more detail, and the R6 article shows the same ideas with an explicit class system.

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.