How to calculate the factorial() of a value in R

The factorial() function in R returns the factorial of a positive integer.

A factorial is a product of that positive integer and all the integers below it until 1.

Figure 1 below shows the mathematical representation of the factorial() function and its corresponding representation in R.

Figure 1: Mathematical representation of the factorial() function and the corresponding representation in R

Syntax


factorial(integer)

Parameter

This function requires a positive integer whose factorial is to be calculated.

Return value

factorial() returns the factorial of the positive integer sent as a parameter.


In the case of a negative value, a warning message is displayed along with NaN.


Code

The following example shows how we can use the factorial() function in R.

#example
a <- factorial(6);
print(paste0("factorial(6): ", a))
b <- factorial(4);
print(paste0("factorial(4): ", b))
c <- factorial(0);
print(paste0("factorial(0): ", c))

Free Resources