Return all combinations or permutations of size k elements out of n.

DESCRIPTION:

Return all 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.

USAGE:

combinations(n, k) 
permutations(n, k = n) 

REQUIRED ARGUMENTS:

n
scalar integer; each combination is a subset of the integers 1:n.
k
scalar integer, number of elements in each combination.

VALUE:

matrix with k rows and choose(n,k) or factorial(n)/factorial(n-k) columns. Each column contains one combination or permutation.

DETAILS:

These function avoid recursion and looping over columns, and are much faster than many other implementations, particularly for large n.

SEE ALSO:

gives the number of combinations, gives the number of permutations, and allows combinations from an arbitrary set, or apply a function to each combination.

EXAMPLES:

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)