R factorial() function - Calculate factorial

R 语言实例R language examples

The R factorial() function is used to calculate the factorial of a positive integer.

Factorial refers to the product of all integers from 1 to n, denoted 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:

  • xInput a non-negative integer or an integer vector.

Examples

# Calculate the factorial of a single value
print(factorial(5))    # 5! = 120
print(factorial(0))    # 0! = 1 (by convention)
print(factorial(10))   # 10! = 3628800

# Calculate the factorial for each element in the vector
x <- c(0, 1, 2, 3, 4, 5)
print(factorial(x))

Executing the above code outputs the following:

[1] 120
[1] 1
[1] 3628800
[1]   1   1   2   6  24 120

factorial() is often used together with choose() when calculating permutations and combinations:

Examples

# Manually calculate the number of permutations P(5, 3) = 5*4*3
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))

Executing the above code outputs the following:

[1] "P(5,3) = 60"
[1] "C(5,3) = 10"
[1] 10

R 语言实例R language examples

Other extensions