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 valuerecursion_Fxn <- function(x) {# intoducing an if statementif (x > 0) {result <- x + recursion_Fxn(x - 1)print(result)# introducing an else block} else {result = 0return(result)}}# calling the functionrecursion_Fxn(6)
Code explanation
- Line 2: We create a recursion function,
recursion_Fxn(). - Line 4: We use the variable
xto loop through the function. - Line 5:
xis added toxwith a decrement of1at every point of recursion. This output is added to another variable,result. - Line 9: The recursion ends when the
resultvariable becomes equal to0. - Line 13: We call the recursion function and pass
6as the argument to the function.