YouTip LogoYouTip

R Func Factorial

# Calculate 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 result:

 120 1 3628800 1 1 2 6 24 120

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

Example

# Manually calculate permutation P(5, 3) = 5*4*3

 n <-5; k <-3

 permutation <-factorial(n)/factorial(n - k)

print(paste("P(5,3) =", permutation))

# Manually calculate combination C(5, 3) = P(5,3) / 3!

 combination <- permutation /factorial(k)

print(paste("C(5,3) =", combination))

# Compare with R's built-in function

print(choose(5, 3))

Executing the above code outputs the following result:

 "P(5,3) = 60" "C(5,3) = 10" 10

Image 4: R Language Example R Examples

← R Func Getwd SetwdR Func Exp β†’