# Recursion in R Programming:

In this tutorial you will learn what is recursion and how to create a recursive function in R programming.

### Recursion:

Recursion is the process in which a function calls itself from its body depending on some condition. If there is no condition given for the call of function, an infinite loop will start hence a logical condition must be given.

A function that calls (from within its body) itself is called recursive function. The main aim is to divide and conquer. Making complex problems to simpler ones. Recursion usually replaces loops in your code and makes your code more readable and brings clarity.

### Example:

The idea of recursion is explained here with the help of a recursive function applied for finding factorial of a number.

Now first question is what is factorial?

Factorial of a given positive integer is defined as the product of all integers from 1 to that specific number. So the factorials of first five positive integers can be calculated as follows:

1! = 1

2! = 1 * 2 = 2

3! = 1 * 2 * 3 = 6

4! = 1 * 2 * 3 * 4 = 24

5! = 1 * 2 * 3 * 4 * 5 = 120

Note: The factorial of 0 is 1.

Well quite simple, isn't it. If you analyze carefully you will note that the factorial of any number is calculated by multiplying that number with the factorial of one less than that number

5! = 5 * 4!

4! = 4 * 3!

3! = 3 * 2!

2! = 2 * 1!

or simply we derive the formula for calculating factorial

n! = n * (n - 1)!

## Recursive Function in R

Now writing the R code for this example.

#Recursion in R: Finding Factorial of a Number

factorial <- function(n) {

if (n == 0)     return (1)

else

return (n * factorial (n-1))

}

You may call this function and provide any positive integer like

> factorial(5)

[1] 120

> factorial(4)

[1] 24

The code becomes more clear and shorter however sometimes it is difficult to find solution to a problem in a recursive way. Moreover, recursive functions may use more memory if they are called for quite a large number of times. The tip is if you have to call a function a few times, recursion is fine but if you have to call a function itself thousands of time, keep an eye on memory usage or better use something else like a for loop or while loop to save memory from repeated function calls.