Download the combinat package from CRAN using
RStudio or the install.packages() command. Then load the
combinat library.
library(combinat)
##
## Attaching package: 'combinat'
## The following object is masked from 'package:utils':
##
## combn
1. Permutations of 1, 2, 3.
permn(3) #use the highest value
## [[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
length(permn(3)) #count the number of permutations
## [1] 6
2. Permutations of the words circle, square,
and triangle.
x <- c("circle", "square", "triangle")
permn(x)
## [[1]]
## [1] "circle" "square" "triangle"
##
## [[2]]
## [1] "circle" "triangle" "square"
##
## [[3]]
## [1] "triangle" "circle" "square"
##
## [[4]]
## [1] "triangle" "square" "circle"
##
## [[5]]
## [1] "square" "triangle" "circle"
##
## [[6]]
## [1] "square" "circle" "triangle"
length(permn(x)) #count the number of permutations
## [1] 6
3. Combinations of 1, 2, 3, 4 taken 3 at a time.
combn(4,3)
## [,1] [,2] [,3] [,4]
## [1,] 1 1 1 2
## [2,] 2 2 3 3
## [3,] 3 4 4 4
ncol(combn(4,3)) #count the number of combinations
## [1] 4
4. Combinations of the words circle, square,
and triangle taken 2 at a time.
x <- c("circle", "square", "triangle")
combn(x, 2)
## [,1] [,2] [,3]
## [1,] "circle" "circle" "square"
## [2,] "square" "triangle" "triangle"
ncol(combn(x, 2)) #count the number of combinations
## [1] 3
Another package in R that can be used in combinatorics is the
gtools package. This is useful when you want to specify if repetition is
allowed or not allowed.
Download the gtools package from CRAN using
RStudio or the install.packages() command. Then load the
gtools library.
library(gtools)
1. Permutations of 39 taken 4 at a time were repetition is
allowed.
x <- nrow(permutations(n=39, r=4, repeats.allowed=T))
print(x)
## [1] 2313441
2. Combinations of the letters from J to M taken 2 at a time
where repetition is not allowed.
x <- c("J", "K", "L", "M")
y <- nrow(combinations(n=4, r=2, v=x, repeats.allowed=F))
print(y)
## [1] 6