k
elements out of
n
.
choose(n,k)
combinations of size
k
elements out of
1:n
,
or all
n! / (n-k)!
permutations of
k
elements out of
1:n
.
combinations(n, k) permutations(n, k = n)
1:n
.
k
rows and
choose(n,k)
or
factorial(n)/factorial(n-k)
columns.
Each column contains one combination or permutation.
These function avoid recursion and looping over columns,
and are much faster than many other implementations, particularly
for large
n
.
combinations(5, 3) permutations(4) permutations(4, 2) # All sets of size 3 from a vector x x <- c("a", "b", "c", "d", "e") matrix(x[combinations(length(x), 3)], 3) # Permutations of a vector x: x <- c("a", "b", "c", "d") matrix(x[permutations(length(x))], length(x)) # A recursive function that does the same thing: recursiveCombinations <- function(n, k){ if(k == 1) matrix(1:n, ncol = 1) else if(k == n) matrix(1:k, nrow = 1) else rbind(recursiveCombinations(n - 1, k), cbind(recursiveCombinations(n - 1, k - 1), n, deparse.level = 0)) } recursiveCombinations(5, 3)