Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

R Recursion


Recursion in R is like a mirror reflecting a mirror—it's a function that calls itself to solve a problem, breaking it down into smaller, simpler instances until it reaches a base case where it doesn't need to call itself anymore.

Let's explain this with an example of a factorial function, which calculates the factorial of a non-negative integer:

Example

# Define a factorial function using recursion
factorial <- function(n) {
if (n == 0) { # Base case: factorial of 0 is 1
return(1)
} else {
return(n * factorial(n - 1)) # Recursive case: n! = n * (n-1)!
}
}

# Calculate the factorial of 5
result <- factorial(5)
print(result) # Output: 120

Here's what's happening:

Recursion can be a powerful tool for solving problems that can be broken down into smaller, similar sub-problems. However, it's important to ensure that there's a base case to prevent infinite recursion and that the problem can indeed be solved using recursion.


Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java