Here, we discuss factorials, permutation and combination in R using the factorial(), choose(), combn() and permn() functions.

Summary of Functions for Counting in R
Function Usage Package
factorial() Calculate factorial value (\(n!\)) base
choose() Calculate number of ways to choose \(k\) items from \(n\) items base
combn() List all the ways to choose \(k\) items from \(n\) items utils
permn() Lists all the possible arrangement of \(n\) items combinat

All functions come with the "base" or "utils" package in the base version of R, except permn() which requires installation of the "combinat" package.

1 \(n\) Factorial in R

\(n! = n \times (n-1) \times ... \times 2 \times 1\) is represented by factorial(n).

Examples:

factorial(3)
[1] 6
factorial(6)
[1] 720

2 Combination in R

Calculate the number of ways to choose \(k\) items from \(n\) items, \(^nC_k = \frac{n!}{k!(n-k)!}\) is represented by choose(n, k).

Examples:

# Number of ways to choose 2 items from 5 items
choose(5, 2)
[1] 10
# Number of ways to choose 5 items from 10 items
choose(10, 5)
[1] 252

To list all the ways to choose \(k\) items from \(n\) items, use the combn() function.

Examples:

# List of ways to choose 2 items from 5 items
combn(1:5, 2)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    2    2    2    3    3     4
[2,]    2    3    4    5    3    4    5    4    5     5
# List of ways to choose 2 letters from A to D
combn(c("A", "B", "C", "D"), 2)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "A"  "A"  "A"  "B"  "B"  "C" 
[2,] "B"  "C"  "D"  "C"  "D"  "D" 
# List of ways to choose 3 letters from A to D
combn(c("A", "B", "C", "D"), 3)
     [,1] [,2] [,3] [,4]
[1,] "A"  "A"  "A"  "B" 
[2,] "B"  "B"  "C"  "C" 
[3,] "C"  "D"  "D"  "D" 

3 Permutation in R

Calculate the number of ways to arrange \(n\) different items, which is \(n!\).

Examples:

# Number of ways to arrange 4 different items
factorial(4)
[1] 24
# Number of ways to arrange 10 different items
factorial(10)
[1] 3628800

To list all the ways to arrange \(n\) different items, use the permn() function after installing the "combinat" package.

Examples:

# Install the package
install.packages("combinat")
# Load the package
library(combinat)
# List all the ways to arrange 3 different items
permn(3)
[[1]]
[1] 1 2 3

[[2]]
[1] 1 3 2

[[3]]
[1] 3 1 2

[[4]]
[1] 3 2 1

[[5]]
[1] 2 3 1

[[6]]
[1] 2 1 3
# List all the ways to arrange A to C
permn(c("A", "B", "C"))
[[1]]
[1] "A" "B" "C"

[[2]]
[1] "A" "C" "B"

[[3]]
[1] "C" "A" "B"

[[4]]
[1] "C" "B" "A"

[[5]]
[1] "B" "C" "A"

[[6]]
[1] "B" "A" "C"

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes