Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R factorial() Function - Calculating Factorials

R factorial() Function - Calculating Factorials

R Language Examples R Language Examples

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:

Example

Calculate the factorial of a single number

print

(

factorial

(

5

)

)

   

5! = 120

print

(

factorial

(

0

)

)

   

0! = 1 (by convention)

print

(

factorial

(

10

)

)

 

10! = 3628800

Calculate the factorial of each element in a vector

x

<-

c

(

0

,

1

,

2

,

3

,

4

,

5

)

print

(

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

)

print

(

paste

(

"P(5,3) ="

, permutation

)

)

Manually calculate the number of combinations C(5, 3) = P(5,3) / 3!

combination

<-

permutation

/

factorial

(

k

)

print

(

paste

(

"C(5,3) ="

, combination

)

)

Compare with R built-in functions

print

(

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 R Language Examples