Re: [R] all combinations with replacement

From: Petr Savicky <savicky_at_praha1.ff.cuni.cz>
Date: Thu, 21 Apr 2011 22:23:18 +0200

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.



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 21 Apr 2011 - 20:31:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 21 Apr 2011 - 21:00:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive