Recursive Functions in R


Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the memory we use the recursion. The recursive function uses the concept of recursion to perform iterative tasks they call themselves, again and again, which acts as a loop. These kinds of functions need a stopping condition so that they can stop looping continuously.

Recursive functions call themselves. They break down the problem into smaller components. The function() calls itself within the original function() on each of the smaller components. After this, the results will be put together to solve the original problem.

Example: Factorial using Recursion in R
factr <- function(n){
if(n==0 || n==1)
{
return(1)
}else
{
return(n*factr(n-1))
}
}

factr(5)
output:
[1] 120

Here, factr(5) calls factr(4), which then calls factr(3), and so on until the input argument x, has reached 1. The function returns 1 and is destroyed. The return value is multiplied with argument value and returned. This process continues until the first function call returns its output, giving us the final result.

Example: Sum of Series Using Recursion
Recursion in R is most useful for finding the sum of self-repeating series. In this example, we will find the sum of squares of a given series of numbers.

Sum = 1^2+2^2+…+N^2

Example:
sum_series <- function(vec){
if(length(vec)<=1)
{
return(vec^2)
}
else
{
return(vec[1]^2+sum_series(vec[-1]))
}
}
series <- c(1:5)
sum_series(series)

output:
[1]55

Key Features of R Recursion

  • The use of recursion, often, makes the code shorter and it also looks clean.
  • It is a simple solution for a few cases.
  • It expresses in a function that calls itself.

Applications of Recursion in R

  • Recursive functions are used in many efficient programming techniques like dynamic programming language(DSL) or divide and conquer algorithms.
  • In dynamic programming, for both top-down as well as bottom-up approaches, recursion is vital for performance.
  • In divide and conquer algorithms, we divide a problem into smaller sub-problems that are easier to solve. The output is then built back up to the top. Recursion has a similar process, which is why it is used to implement such algorithms.
  • In its essence, recursion is the process of breaking down a problem into many smaller problems, these smaller problems are further broken down until the problem left is trivial. The solution is then built back up piece by piece.

Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types