What is Recursion and Recursive Function in R Programming?
In the R functions tutorial, we briefly looked at recursive functions. Now, in this article, we will cover their full scope. We will study the concept of recursion in programming languages. We will learn what recursive functions are. And also learn where recursive functions are useful through a few examples. This tutorial is surely going to be very interesting, so, get ready!
What is Recursion in R?
Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. We can call a function, declared in the global environment of the R session, from the global environment or the function’s local environment.
Recursion in R is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again.
What are Recursive Functions?
Recursive functions are functions that use the concept of recursion to perform repetitive or iterative tasks. They call themselves, again and again, this imitates a loop.
Recursive functions need a stopping condition so that they do not keep looping indefinitely.
Why use Recursive Functions?
Loops increase the memory and time requirements of any program. There are many cases where using a recursive function is a better alternative than using a loop. Once a function has returned its output, its local environment is destroyed along with any temporary variables and other memory allocations. This frees up the memory used by the function.
The same goes for recursive functions. As soon as they return the output, their local environments are destroyed, thus, freeing up the memory used by every iteration.
Applications of Recursion in R
Recursive functions are used in many efficient programming techniques like dynamic programming 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.
Now, let us look at a few examples of recursive functions.
1. Factorial using Recursion in R
We can find the factorial of a number using recursion in R like this:
Code:
rec_fac <- function(x){ if(x==0 || x==1){ return(1) } else { return(x*rec_fac(x-1)) } }
Output:
Note: Here, rec_fac(5)
calls rec_fac(4)
, which then calls rec_fac(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.
2. Sum of Natural Numbers using Recursion
Finding the sum of natural numbers is also a good use for recursive functions. In this example, we have naturals, a vector with 30 natural numbers (integers). The function sum_nat
finds the sum of the numbers using recursion.
Code:
sum_nat <- function(vec){ if(length(vec)<=1){ return(vec) } else { return(vec[1]+sum_nat(vec[-1])) } } naturals <- c(1:30) sum_nat(naturals)
Output:
3. 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 = 12+22+…+N2
Code:
sum_series <- function(vec){ if(length(vec)<=1){ return(vec^2) }else{ return(vec[1]^2+sum_series(vec[-1])) } } series <- c(1:10) sum_series(series)
Output:
4. Using Recursion to Sort a Numeric Vector
We can also use recursive functions to sort numeric vectors. In the following example, we split the given vector into two smaller ones containing elements larger than or smaller than the first element. These smaller vectors are then further sorted using the same function until the length of the vectors is 1 or 0. They are then arranged in order and returned.
Code:
quicksort <- function(vec){ if(length(vec)<=1){ return(vec) } else { subject <- vec[1] predicate <- vec[-1] large <- predicate[predicate>subject] small <- predicate[predicate<=subject] large <- quicksort(large) small <- quicksort(small) return(c(small,subject,large)) } } quicksort(c(4,82,23,0,-15,16,31,-29))
Output:
Let us go through what exactly is happening in the above example.
Step – 1. The quicksort function selects the first element of the input vector and compares it with the rest of the elements.
Step – 2. It stores the elements larger than the subject element in the large vector and the smaller elements in the small vector.
Step – 3. It then calls itself to sort the large and small vectors.
Step – 4. This process repeats until the input vector has a length less than or equal to 1. In such a case, the function returns the input vector as it is.
Step – 5. The function then arranges the vector in order as shown (small, subject, large) and returns this output.
Step – 6. The predecessors arrange the returned output in the same order and pass it forward until the first function returns the final output.
Summary
In this tutorial, we learned about recursive functions and recursion in R. We looked at a few examples and saw how the functions called themselves to solve a part of the bigger problem.
Recursion is the process of breaking down problems into parts to solve them. It reduces the time and space complexity of a program and makes it more efficient.
R offers many functions like –
which makes a beginner’s life extremely easy.
Any difficulty while practicing recursive functions?
Ask our TechVidvan experts in the comment section below.
Keep Learning!!