R Recursion
Recursion in R occurs when a function calls itself. It is a powerful technique used to solve problems that can be broken down into smaller, similar sub-problems. However, care must be taken to ensure the function has a base case to prevent infinite recursion.
Key Topics
Recursion Example
# Example of a recursive function
factorial <- function(n) {
if (n <= 1) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
# Calling the recursive function
factorial(5)
Output:
[1] 120
Code Explanation: The factorial
function calculates the factorial of n
by calling itself with n - 1
until n
is less than or equal to 1. The base case n <= 1
stops the recursion and returns 1.
Base Case Importance
A base case is essential in a recursive function to terminate the recursion. Without a base case, the function would continue to call itself indefinitely, leading to a stack overflow error.
Key Takeaways
- Recursion is useful for problems that can be divided into smaller sub-problems.
- A base case is necessary to stop the recursive calls and prevent infinite recursion.
- Recursive functions can be elegant but may be less efficient for deep recursion due to memory limitations.