Environments in R store variables and their values. Closures are functions that remember the environment where they were created. This helps keep data safe and lets functions use variables even after the original place is gone.
When you want a function to remember some settings or data for later use.
When you want to create a function that changes its behavior based on stored information.
When you want to avoid using global variables but still keep data accessible inside functions.
When you want to create multiple similar functions that each keep their own data.
When you want to write cleaner code by bundling data and functions together.
Syntax
R Programming
make_function <- function(x) {
y <- x
function(z) {
y + z
}
}
The outer function creates an environment where y is stored.
The inner function is a closure that can use y even after make_function finishes.
Examples
This creates a closure that adds 5 to any number given.
R Programming
add_five <- function() {
n <- 5
function(x) {
x + n
}
}
This closure multiplies a number by a stored factor.
The inner function modifies 'count' in the parent environment using <<- and increments it by 1 each call.
Step 2: Trace the calls to counter()
First call returns 1 (0+1), second call returns 2 (1+1).
Final Answer:
[1] 1 followed by [1] 2 -> Option D
Quick Check:
Closure increments count with <<- [OK]
Hint: <<- changes outer variable, so count increases each call [OK]
Common Mistakes:
Thinking count resets each call
Confusing <- with <<- operator
Expecting error due to variable scope
4. Identify the error in this R code that tries to create a closure:
make_adder <- function(x) {
function(y) {
x + y
}
}
add5 <- make_adder(5)
add5(3)
rm(x)
medium
A. The function make_adder is missing a return statement
B. Removing 'x' breaks the closure, causing an error on add5(3)
C. No error; code runs fine
D. The inner function should use <<- to modify x
Solution
Step 1: Understand closure variable dependency
The inner function depends on 'x' stored in its own dedicated environment created by make_adder.
Step 2: Effect of removing 'x'
rm(x) removes 'x' from the global environment if it exists, but the closure's environment retains its own 'x' = 5, so add5(3) works fine.
Final Answer:
No error; code runs fine -> Option C
Quick Check:
Closure environments are independent of global [OK]
Hint: rm(x) doesn't affect closure's private x [OK]
Common Mistakes:
Thinking functions need explicit return
Believing <<- is needed to read outer variables
Mistakenly thinking rm(x) removes closure's x
5. You want to create a function in R that remembers a secret number and returns a function to check guesses. Which approach correctly uses closures to keep the secret safe?
secret_keeper <- function(secret) { function(guess) { guess == secret } } returns a function that compares guess to secret stored in the closure environment, keeping secret safe.