R factorial() Function - Calculating Factorials
The R factorial() function is used to calculate the factorial of a positive integer.
A factorial is the product of multiplying from 1 up to n, written as n!. It is very common in permutations, combinations, and probability calculations.
The syntax of the factorial() function is as follows:
factorial(x)
Parameter Description:
-
x Input a non-negative integer or a vector of integers.
Example
Calculate the factorial of a single number
(
factorial
(
5
)
)
5! = 120
(
factorial
(
0
)
)
0! = 1 (by convention)
(
factorial
(
10
)
)
10! = 3628800
Calculate the factorial of each element in a vector
x
<-
c
(
0
,
1
,
2
,
3
,
4
,
5
)
(
factorial
(
x
)
)
The output of the code above is:
[1] 120
[1] 1
[1] 3628800
[1] 1 1 2 6 24 120
factorial() is often used together with choose() when calculating the number of permutations and combinations:
Example
Manually calculate the number of permutations P(5, 3) = 543
n
<-
5
;
k
<-
3
permutation
<-
factorial
(
n
)
/
factorial
(
n
k
)
(
paste
(
"P(5,3) ="
, permutation
)
)
Manually calculate the number of combinations C(5, 3) = P(5,3) / 3!
combination
<-
permutation
/
factorial
(
k
)
(
paste
(
"C(5,3) ="
, combination
)
)
Compare with R built-in functions
(
choose
(
5
,
3
)
)
The output of the code above is:
[1] "P(5,3) = 60"
[1] "C(5,3) = 10"
[1] 10
R Language Examples