R Nested Functions & Recursion
Functions can call other functions, be defined inside other functions, and even call themselves. These three ideas let you break big problems into small, reusable pieces.
Calling a function inside another call
The simplest kind of nesting is passing the result of one function as the argument of another. R evaluates the innermost call first:
values <- c(3.14159, 2.71828, 1.41421)
round(sum(sqrt(values)), 2)
toupper(substr("statistics", 1, 4))[1] 4.61
[1] "STAT"
Deep nesting gets hard to read. The pipe |> writes the same steps from left to right:
values <- c(3.14159, 2.71828, 1.41421)
values |> sqrt() |> sum() |> round(2)[1] 4.61
Defining a function inside a function
A function defined inside another one is a helper that only exists while the outer function runs. It can see the outer function's variables:
summarise_scores <- function(scores, pass_mark = 50) {
pct <- function(x) paste0(round(100 * x), "%")
passed <- scores >= pass_mark
cat("Pass rate:", pct(mean(passed)), "\n")
cat("Top score:", max(scores), "\n")
}
summarise_scores(c(45, 67, 82, 39, 91))
exists("pct")Pass rate: 60%
Top score: 91
[1] FALSE
Functions that return functions
The outer function can also return the inner one. The returned function remembers the variables of the call that created it; this is called a closure:
make_multiplier <- function(factor) {
function(x) x * factor
}
double <- make_multiplier(2)
triple <- make_multiplier(3)
double(10)
triple(10)
triple(1:4)[1] 20
[1] 30
[1] 3 6 9 12
double and triple share the same code but each keeps its own factor. The Environments & Scope lesson explains how this works.
Recursion
A recursive function calls itself on a smaller version of the problem. Every recursive function needs a base case that stops the chain.
factorial_rec <- function(n) {
if (n <= 1) return(1) # base case
n * factorial_rec(n - 1) # recursive case
}
factorial_rec(5)
factorial_rec(10)
factorial(10) # the built-in agrees[1] 120
[1] 3628800
[1] 3628800
The call factorial_rec(3) unfolds as 3 * factorial_rec(2) → 3 * 2 * factorial_rec(1) → 3 * 2 * 1.
Recursion on structures
Recursion shines when the data itself is nested, for example a list that contains lists. This function adds up every number, however deep it is hidden:
deep_sum <- function(x) {
if (is.numeric(x)) return(sum(x))
total <- 0
for (item in x) total <- total + deep_sum(item)
total
}
data <- list(1, list(2, 3, list(4, 5)), c(6, 7))
deep_sum(data)[1] 28
Recursion vs. loops
Recursion is elegant but every call uses memory, and R has a limit on how deep calls can go (expressions option, 5000 by default). A naive recursive Fibonacci also repeats a lot of work. For long sequences, a loop or a vectorised function is usually better:
fib <- function(n) if (n <= 2) 1 else fib(n - 1) + fib(n - 2)
sapply(1:10, fib) [1] 1 1 2 3 5 8 13 21 34 55
Tip:
Recall()calls the current function recursively without repeating its name, which keeps working even if you rename the function.
Test yourself
What does every recursive function need?
- A loop
- A base case that stops the recursion
- A global variable
- The
...argument
Given add <- function(a) function(b) a + b, what is add(2)(5)?
- 2
- 5
- 7
- An error
Can code outside a function call a helper function defined inside it?
- Yes, always
- No, the helper only exists inside the outer function's environment
- Only if it has no arguments
- Only with
<<-