factorial in R: How to Calculate Factorial of Number in R

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 5, which can be denoted as 5! is 5*4*3*2*1* = 120. You can not calculate the factorial of a negative number, and the factorial of zero is one you can denote as 0! = 1.

R language has great support for mathematical calculations, and it does provide a function called factorial() that will help you find the factorial of any integer.

factorial in R

The factorial() in R is a built-in function that calculates the factorial of a number without writing manual complete code to compute the factorial. The factorial() function takes a number as an argument and returns its factor.

To calculate the factorial of a number in R, use the factorial() function.

Syntax

factorial(data)

Parameters

data: The data is a number whose factorial has to be calculated.

Return Value

The factorial() method returns the factorial of the desired number.

Example

ft1 <- factorial(4)
ft2 <- factorial(-3)
ft3 <- factorial(0)

print(ft1)
print(ft2)
print(ft3)

Output

[1] 24
[1] NaN
[1] 1

The first output is produced based on 4 x 3 x 2 x 1 = 24.

If we find the factorial of the negative integer, then it will return NaN.

You will also get a warning message like the one below because of the negative integer.

Warning message:
In gamma(x + 1) : NaNs produced

The factorial of 0 is 1.

Find the factorial of Vector in R

To calculate the factorial of a vector in R, use the factorial() function.

rv <- c(0, 1, 2, 3, 4)
rvf <- factorial(rv)
print(rvf)

Output

[1] 1 1 2 6 24

Find factorial of the user input number.

To get the input from the user, use the readline() function.

See the below code.

int <- as.integer(readline(prompt = "Please enter a number"))
facto <- 1

if (int < 0) {
 print("Negative numbers are not allowed")
} else if (int == 0) {
 print("The factorial of 0 is 1")
} else {
 facto <- factorial(int)
 print(facto)
}

Output

Please enter a number: 7
[1] 5040

The factorial of 7 is 5040.

That is it for calculating the factorial of a number in R language.

Leave a Comment