Recursion in R Programming Language

Our example demonstrates recursion in R. Here’s the full source code:

# This fact function calls itself until it reaches the
# base case of fact(0).
fact <- function(n) {
  if (n == 0) {
    return(1)
  }
  return(n * fact(n - 1))
}

# Main execution
main <- function() {
  print(fact(7))
  
  # In R, we don't need to declare the function type explicitly before defining it.
  # We can directly define and use the recursive function.
  fib <- function(n) {
    if (n < 2) {
      return(n)
    }
    return(fib(n - 1) + fib(n - 2))
  }
  
  print(fib(7))
}

# Run the main function
main()

To run the program, save it as recursion.R and use Rscript:

$ Rscript recursion.R
[1] 5040
[1] 13

In this R example, we’ve implemented both the factorial and Fibonacci functions using recursion.

The fact function calculates the factorial of a number recursively. It continues to call itself with n-1 until it reaches the base case of 0.

For the Fibonacci sequence, we’ve defined the fib function inside the main function. In R, we don’t need to declare the function type explicitly before defining it, as we do in some other languages. We can directly define and use the recursive function.

Both functions demonstrate how recursion can be used to solve problems by breaking them down into smaller, similar sub-problems.

Remember that while recursion can lead to elegant solutions for some problems, it can also be less efficient for larger inputs due to the overhead of multiple function calls. In such cases, iterative solutions or dynamic programming approaches might be more suitable.