Recursive function in R

In this tutorial on recursive function, you will master everything about a unique process in a function called Recursion. Also, you will see some problems that are well suited to be solved by recursion, such as number factorial, Fibonacci series, etc.

Like in other programming languages Recursive functions do exist in R programming language. When a function calls itself it is recursive function.Recusrsion helps to break down a large problem (large set of instructions) to smaller chunks.

The original function (factorial)is called within the function() during its execution.

What is recursion?

Recursion, generally, means the process of the repetitive calling of a function by itself to work on smaller problems. A function is said to be recursive if a function calls itself and such function calls are named recursive calls. Precisely, the recursive calls end when it reaches the base case.

In R Programming, Recursion and iteration go hand in hand but both notch some specific tasks designed for them. For instance, recursion is useful for performing some mathematical calculations, sorting, searching,  traversing, etc. However, it is not applicable to all problems. So we can say that it is nothing but a type of customized function. Some problems that well 

The use of recursion in R is an elegant way to reduce the code size. 

Syntax of Recursive Function


function_name<- function(){  # recursive function
  ..............           
  function_name()   #recursive call 
  ..............     
}
function_name()     #function call


Working of Recursive Function in R

Working of recursion in R can be best visualized as below to make it more understandable.

ls fn snippet

Example of Recursion in R Programming

Find below a simple r program that will find factorial of a number, through a recursive function.

Factorial using Recursion


factorial<- function(num) {
if(num <= 1) {
return(1)
} else { 
return(num * factorial(num-1))
}
}

print(paste("The factorial of 5 is",factorial(5)))


Output will be


[1] "The factorial of 5 is 120"

We call a function factorial(5) to find the value of 5 !, the function returns a value like 5 x factorial(5-1) ie., inside the factorial function it again called the same function with next number 4. this will continue till returns a 1 with factorial(0). Finally, the product of each return value will give an answer 120.

ls fn snippet