recursion function r
r <- function(n) {
if (n <= 0) {
return(1)
} else {
return(n * r(n - 1))
}
}
Explanation:
- The function
r
is defined to take one parameter,n
. - Inside the function, there is an
if
statement to check ifn
is less than or equal to 0. - If the condition is true, the function returns 1. This is the base case for the recursion.
- If the condition is false (i.e.,
n
is greater than 0), the function calculates the factorial ofn
using recursion. - It calls itself with the argument
n - 1
and multiplies the result byn
. - The recursion continues until the base case is reached (when
n
becomes 0 or negative). - The final result is the product of all the numbers from
n
down to 1, which is the factorial of the original inputn
.