Search⌘ K
AI Features

Recursion

Understand recursive functions in R by learning how a function can call itself. Discover the importance of base cases and recursive cases to control repetition and avoid errors. This lesson helps you apply recursion effectively for tasks requiring repeated function execution in data analysis.

Recursive Functions

We can also call the function itself from its body. Such a function is called a recursive function. A recursive function is a function that calls itself during its execution.

Recursion enables the function to repeat itself several times, collecting the result at the end of each iteration.

Components of a Recursive Function

Each recursive function has two parts:

  • Base Case: The base case is where the call to the function stops, i.e., it does not make any subsequent recursive calls.

  • Recursive Case: The recursive case is where the function calls itself again and again until it reaches the base case.

Let’s have a look at an example. Here, we print numbers from 1010 to 11 using recursion. We call the function printNumbers() inside itself.

R
printNumbers <- function(myNumber)
{
if (myNumber == 1) # Base Case
{
print(myNumber)
} else
{
print(myNumber)
printNumbers(myNumber - 1) # Recursive Case
}
}
# Driver Code
test = 10
printNumbers(test)

Be very careful while using recursion because it can lead to errors if used carelessly.