[R] all combinations with replacement

Petr Savicky savicky at praha1.ff.cuni.cz
Thu Apr 21 22:23:18 CEST 2011


On Thu, Apr 21, 2011 at 12:52:34PM -0700, Kehl Dániel wrote:
> Thank you.
> I only need those where the rowsum = n.
> I could choose those with code, but I dont think it is efficient that way.

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.



More information about the R-help mailing list