Recursive functions help solve problems by calling themselves with smaller parts of the problem. This makes some tasks easier to understand and write.
0
0
Recursive functions in R Programming
Introduction
When you want to break a big problem into smaller similar problems, like calculating factorial.
When working with data that has a repeating structure, like folders inside folders.
When you want to explore all possibilities, like in puzzles or games.
When you want to process items that depend on previous results, like Fibonacci numbers.
Syntax
R Programming
recursive_function <- function(parameter) {
if (base_case_condition) {
return(base_case_value)
} else {
return(recursive_function(smaller_parameter))
}
}The base case stops the recursion to avoid infinite loops.
Each recursive call should work on a smaller or simpler input.
Examples
Calculates factorial of a number using recursion.
R Programming
factorial <- function(n) {
if (n == 0) {
return(1) # base case
} else {
return(n * factorial(n - 1))
}
}Shows the base case where recursion stops immediately.
R Programming
factorial(0) # returns 1, base case example
Recursion calls factorial(0) next, then multiplies.
R Programming
factorial(1) # returns 1, smallest positive number factorial
Example of multiple recursive calls until base case.
R Programming
factorial(5) # returns 120, recursive calls multiply down to base case
Sample Program
This program defines a recursive function to calculate factorial. It prints the factorial of 5 and the base case factorial of 0.
R Programming
factorial <- function(number) {
if (number == 0) {
return(1) # base case
} else {
return(number * factorial(number - 1))
}
}
# Print factorial of 5
print(paste("Factorial of 5 is", factorial(5)))
# Print factorial of 0 (edge case)
print(paste("Factorial of 0 is", factorial(0)))OutputSuccess
Important Notes
Time complexity is O(n) because the function calls itself n times.
Space complexity is O(n) due to the call stack growing with each call.
Common mistake: forgetting the base case causes infinite recursion and crashes.
Use recursion when the problem naturally breaks down into smaller similar problems; otherwise, loops might be simpler.
Summary
Recursive functions call themselves with smaller inputs.
Always include a base case to stop recursion.
Useful for problems like factorial, Fibonacci, and tree traversal.