How to perform a recursion in R

Overview

Recursion in R is used to describe a situation in which a function calls itself. This condition forms a loop so that whenever the function is called, it calls itself again and again.

Recursion in R allows us to loop through data to reach a result.

Example

# creating a function with x as its parameter value
recursion_Fxn <- function(x) {
# intoducing an if statement
if (x > 0) {
result <- x + recursion_Fxn(x - 1)
print(result)
# introducing an else block
} else {
result = 0
return(result)
}
}
# calling the function
recursion_Fxn(6)

Code explanation

  • Line 2: We create a recursion function, recursion_Fxn().
  • Line 4: We use the variable x to loop through the function.
  • Line 5: x is added to x with a decrement of 1 at every point of recursion. This output is added to another variable, result.
  • Line 9: The recursion ends when the result variable becomes equal to 0.
  • Line 13: We call the recursion function and pass 6 as the argument to the function.

Free Resources