ZetCode

R recursion

last modified November 20, 2026

A recursive function calls itself on a smaller input and stops when the input reaches a base case. R supports recursion directly: a function can refer to its own name, and Recall refers to the function being called without repeating the name. Recursion is a natural fit for nested data, divide-and-conquer algorithms, and definitions that are themselves recursive. This article starts with a factorial, then moves to vectors, lists, binary search, trees, and the Towers of Hanoi. The examples use R 4.5.2.

Base case and recursive case

Every recursive function needs a base case that returns without another call, and a recursive case that makes the problem smaller. The factorial function has the base case n <= 1 and the recursive case n * product(n - 1). The argument decreases by one on every call, so the recursion must reach the base case.

recursive-product.R
product <- function(n) {
  if (n <= 1) return(1)
  n * product(n - 1)
}
cat("5! =", product(5), "\n")
cat("0! =", product(0), "\n")
cat("10! =", product(10), "\n")

product(5) expands to 5 * 4 * 3 * 2 * 1 and returns 120. product(0) hits the base case immediately and returns 1, which is the conventional value of zero factorial. product(10) returns 3628800. If the recursive call did not shrink the argument, the function would never reach the base case.

$ Rscript recursive-product.R
5! = 120 
0! = 1 
10! = 3628800 

The call stack and unwinding

R keeps a frame for every active call. A recursive call adds a frame, and the frames are removed in the reverse order when the calls return. Printing before and after the recursive call shows both directions: the numbers descend to the base case, then the back from lines climb out again.

countdown.R
countdown <- function(n) {
  if (n == 0) {
    cat("liftoff\n")
    return(invisible(NULL))
  }
  cat(n, "\n")
  countdown(n - 1)
  cat("back from", n, "\n")
}
countdown(3)

The first three lines descend from 3 to 1, then liftoff ends the recursion. The remaining lines are printed as each frame resumes: the call with n = 1 returns first, then 2, then 3. The output order is the call stack in action. A recursive function therefore uses memory proportional to the depth of the recursion.

$ Rscript countdown.R
3 
2 
1 
liftoff
back from 1 
back from 2 
back from 3 

Recursion over a vector

A vector can be consumed one element at a time. sum_values adds the first element to the sum of the rest; the base case is the empty vector. x[-1] returns a new vector without the first element, so the input shrinks on every call. This is clear but not efficient for long vectors, because every call copies the remaining elements.

recursive-sum.R
sum_values <- function(x) {
  if (length(x) == 0) return(0)
  x[1] + sum_values(x[-1])
}
values <- c(4, 7, 2, 9)
cat("sum:", sum_values(values), "\n")
cat("length of input:", length(values), "\n")

The vector c(4, 7, 2, 9) becomes c(7, 2, 9), then c(2, 9), then 9, then the empty vector. The additions happen on the way back: 9, 11, 18, 22. The original vector is unchanged at the end. For a long vector the copying cost is quadratic, which is why sum is written in C rather than as this recursion.

$ Rscript recursive-sum.R
sum: 22 
length of input: 4 

Recursion over a nested list

Lists can contain other lists, so their depth is not known in advance. A recursive function can handle a leaf and a branch with two cases: a non-list value is returned as it is, and a list is processed element by element. The loop visits every child, and each child may start another level of recursion.

nested-list.R
sum_leaves <- function(x) {
  if (!is.list(x)) return(x)
  total <- 0
  for (item in x) {
    total <- total + sum_leaves(item)
  }
  total
}
nested <- list(1, list(2, 3), list(list(4), 5))
cat("sum of leaves:", sum_leaves(nested), "\n")
str(nested, max.level = 3)

The nested object has three top-level elements: the number 1, a list of two numbers, and a list that contains another list. sum_leaves adds 1, then recurses into the second element and adds 2 and 3, then into the third and adds 4 and 5. The total is 15. str shows the same structure with one line per level, which makes the two cases easy to see.

$ Rscript nested-list.R
sum of leaves: 15 
List of 3
 $ : num 1
 $ :List of 2
  ..$ : num 2
  ..$ : num 3
 $ :List of 2
  ..$ :List of 1
  .. ..$ : num 4
  ..$ : num 5

Divide and conquer: binary search

Binary search halves a sorted vector on every call. It compares the middle element with the target, then recurses into the left or right half. The base case is an empty range, where the target is absent. The defaults lo and hi describe the current range, so the recursive calls pass new bounds instead of copying the vector.

binary-search.R
binary_search <- function(x, target, lo = 1, hi = length(x)) {
  if (lo > hi) return(NA_integer_)
  mid <- (lo + hi) %/% 2
  if (x[mid] == target) return(mid)
  if (x[mid] < target) {
    binary_search(x, target, mid + 1, hi)
  } else {
    binary_search(x, target, lo, mid - 1)
  }
}
values <- c(2, 4, 6, 8, 10, 12, 14)
cat("index of 10:", binary_search(values, 10), "\n")
cat("index of 5:", binary_search(values, 5), "\n")

The first search finds 10 at index 5. The second search narrows the range until lo passes hi and returns NA_integer_, which prints as NA. The number of calls is at most the logarithm of the vector length, so a vector with a million elements needs about twenty comparisons. The vector must be sorted; binary search on unsorted data returns an arbitrary answer.

$ Rscript binary-search.R
index of 10: 5 
index of 5: NA 

Recursion with Recall

Recall calls the function that is currently being evaluated. It is useful when the function is anonymous or when its name may change, because the recursive call does not repeat the name. The Euclidean algorithm is a short example: the greatest common divisor of a and b is the greatest common divisor of b and a %% b, and the base case is b == 0.

euclid.R
gcd <- function(a, b) {
  if (b == 0) return(a)
  Recall(b, a %% b)
}
cat("gcd(48, 18):", gcd(48, 18), "\n")
cat("gcd(1071, 462):", gcd(1071, 462), "\n")

gcd(48, 18) becomes gcd(18, 12), then gcd(12, 6), then gcd(6, 0), which returns 6. The second call reduces 1071 and 462 in the same way and returns 21. Recall receives the new arguments and starts another evaluation of the same closure. The recursive call does not repeat the function name, so renaming the function cannot break it.

$ Rscript euclid.R
gcd(48, 18): 6 
gcd(1071, 462): 21 

Tree recursion and cost

A function that calls itself twice creates a tree of calls rather than a chain. The naive Fibonacci implementation is the standard example: fib(n) calls fib(n - 1) and fib(n - 2), and the two branches overlap. The result is correct, but the number of calls grows exponentially. The calls counter makes the cost visible.

fib.R
calls <- 0
fib <- function(n) {
  calls <<- calls + 1
  if (n <= 1) return(n)
  fib(n - 1) + fib(n - 2)
}
cat("fib(10):", fib(10), "\n")
cat("calls:", calls, "\n")

fib(10) returns 55 after 177 calls. The same subproblems are computed many times: fib(7) is evaluated in both the fib(9) and fib(8) branches, and so on down the tree. Memoization, shown in the closures article, stores each result and reduces the call count to linear. The naive version is still useful for small inputs and for explaining the cost model.

$ Rscript fib.R
fib(10): 55 
calls: 177 

Stack depth

R limits the number of nested expressions and the size of the C stack. The expressions option controls the first limit and defaults to 5000. A depth of 100 is safe, but a depth of 500 with the limit lowered to 200 signals an error. The exact limit depends on the build and on the available stack, so a recursive function should not rely on a particular depth.

stack-depth.R
depth <- function(n) {
  if (n == 0) return(0)
  1 + depth(n - 1)
}
cat("depth 100:", depth(100), "\n")
cat("expression limit:", getOption("expressions"), "\n")
options(expressions = 200)
failure <- tryCatch(depth(500), error = function(e) conditionMessage(e))
cat("failure:", failure, "\n")

The controlled call at depth 100 returns 100. With options(expressions = 200), the call at depth 500 exceeds the limit and tryCatch captures a message that begins with evaluation nested too deeply. The option lasts for the rest of the session; a script that changes it should save the old value if later code depends on it. Deep recursion is usually better replaced by an explicit loop or by a divide-and-conquer algorithm with logarithmic depth.

$ Rscript stack-depth.R
depth 100: 100 
expression limit: 5000 
failure: evaluation nested too deeply: infinite recursion / options(expressions=)? 

A complete example: Towers of Hanoi

The Towers of Hanoi puzzle has a recursive solution. To move n disks from one peg to another, move the top n - 1 disks to the spare peg, move the largest disk to the target, then move the n - 1 disks from the spare peg onto the target. The base case is zero disks, which needs no moves. The function returns the list of moves instead of printing them, so the caller can count or display them.

hanoi.R
hanoi <- function(n, from = "A", to = "C", via = "B") {
  if (n == 0) return(character(0))
  c(
    hanoi(n - 1, from, via, to),
    paste("disk", n, ":", from, "->", to),
    hanoi(n - 1, via, to, from)
  )
}
moves <- hanoi(3)
cat(moves, sep = "\n")
cat("moves:", length(moves), "expected:", 2^3 - 1, "\n")

hanoi(3) returns seven moves, which is 2^3 - 1. The first three moves clear the two smaller disks to peg B, the fourth moves the largest disk to C, and the last three move the smaller disks onto it. The recursive calls are on n - 1, so the recursion depth is n. For 64 disks the solution has 2^64 - 1 moves, which shows why the puzzle is used as an example of exponential growth.

$ Rscript hanoi.R
disk 1 : A -> C
disk 2 : A -> B
disk 1 : C -> B
disk 3 : A -> C
disk 1 : B -> A
disk 2 : B -> C
disk 1 : A -> C
moves: 7 expected: 7 

Next steps

The closures article shows how to memoize a recursive function, and the performance article measures the cost of a call and profiles a loop. The functions article covers the argument matching that a recursive call uses, and the apply family article shows iteration over lists without explicit recursion. The environments article explains the frames that the call stack creates.

Source

R manual: Recall

R manual: options

Wikipedia: Tower of Hanoi

In this article a function called itself until it reached a base case. We followed the call stack through a countdown, consumed a vector and a nested list one level at a time, and used divide and conquer for binary search. The Euclidean algorithm showed Recall without a repeated function name, the Fibonacci example exposed the cost of tree recursion, and the depth section showed the limit that stops runaway recursion. The final example returned the moves of the Towers of Hanoi and counted them. The closures article shows how to cache the results of a recursive function, which turns the exponential Fibonacci version into a linear one.

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.