This function generates all the combinations of selecting k items from n items.
The results are in lexicographical order.
combinations(
x = NULL,
k = NULL,
n = NULL,
v = NULL,
freq = NULL,
replace = FALSE,
layout = NULL,
nitem = -1L,
skip = NULL,
index = NULL,
nsample = NULL,
drop = NULL
)an integer or a vector, will be treated as n if integer; otherwise, will be treated as v.
Should not be specified together with n and v.
an integer, the number of items drawn, defaults to n if freq is NULL else sum(freq)
an integer, the total number of items, its value may be implicitly deduced from length(v) or length(freq)
a vector to be drawn, defaults to 1:n.
an integer vector of item repeat frequencies
an logical to draw items with replacement
if "row", "column" or "list" is specified, the returned value would be a "row-major" matrix, a "column-major" matrix or a list respectively
number of combinations required, usually used with skip
the number of combinations skipped
a vector of indices of the desired combinations
sampling random combinations
vectorize a matrix or unlist a list
icombinations for iterating combinations and ncombinations to calculate number of combinations
# choose 2 from 4
combinations(4, 2)
#> [,1] [,2]
#> [1,] 1 2
#> [2,] 1 3
#> [3,] 1 4
#> [4,] 2 3
#> [5,] 2 4
#> [6,] 3 4
combinations(LETTERS[1:3], k = 2)
#> [,1] [,2]
#> [1,] "A" "B"
#> [2,] "A" "C"
#> [3,] "B" "C"
# multiset with frequencies c(2, 3)
combinations(k = 3, freq = c(2, 3))
#> [,1] [,2] [,3]
#> [1,] 1 1 2
#> [2,] 1 2 2
#> [3,] 2 2 2
# with replacement
combinations(4, 2, replace = TRUE)
#> [,1] [,2]
#> [1,] 1 1
#> [2,] 1 2
#> [3,] 1 3
#> [4,] 1 4
#> [5,] 2 2
#> [6,] 2 3
#> [7,] 2 4
#> [8,] 3 3
#> [9,] 3 4
#> [10,] 4 4
# column major
combinations(4, 2, layout = "column")
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 1 1 2 2 3
#> [2,] 2 3 4 3 4 4
# list output
combinations(4, 2, layout = "list")
#> [[1]]
#> [1] 1 2
#>
#> [[2]]
#> [1] 1 3
#>
#> [[3]]
#> [1] 1 4
#>
#> [[4]]
#> [1] 2 3
#>
#> [[5]]
#> [1] 2 4
#>
#> [[6]]
#> [1] 3 4
#>
# specifc range of combinations
combinations(4, 2, nitem = 2, skip = 3)
#> [,1] [,2]
#> [1,] 2 3
#> [2,] 2 4
# specific combinations
combinations(4, 2, index = c(3, 5))
#> [,1] [,2]
#> [1,] 1 4
#> [2,] 2 4
# random combinations
combinations(4, 2, nsample = 3)
#> [,1] [,2]
#> [1,] 1 2
#> [2,] 3 4
#> [3,] 2 3
# zero sized combinations
dim(combinations(5, 0))
#> [1] 1 0
dim(combinations(5, 6))
#> [1] 0 6
dim(combinations(0, 0))
#> [1] 1 0
dim(combinations(0, 1))
#> [1] 0 1