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.
# 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)
recursion_Fxn()
.x
to loop through the function.x
is added to x
with a decrement of 1
at every point of recursion. This output is added to another variable, result
.result
variable becomes equal to 0
.6
as the argument to the function.