Skip to content
Prev 257673 / 398502 Next

all combinations with replacement

On Thu, Apr 21, 2011 at 12:52:34PM -0700, Kehl D?niel wrote:
Efficiency of using expand.grid() may be improved, if expand.grid()
is used only to k-1 columns, then the k-th column is computed and
the rows with a negative value in it are discarded.

  n <- 6
  k <- 3
  a <- as.matrix(expand.grid(rep(list(0:n), k - 1)))
  a <- cbind(a, n - rowSums(a))
  colnames(a) <- NULL
  a <- a[0 <= a[, k], ]
  nrow(a) == choose(n + k - 1, k - 1)
  [1] TRUE

In this way, we select choose(n + k - 1, k - 1) among n^(k - 1)
rows and not among n^k.

Hope this helps.

Petr Savicky.