Skip to content

all combinations with replacement

6 messages · Kehl Dániel, Dimitris Rizopoulos, Jorge Ivan Velez +2 more

#
Dear all,

is there an easy way to get all possible combinations (?) with replacement.
If n=6, k=3, i want something like

0 0 6
0 5 1
0 4 2
0 3 3
0 2 4
.
.
.
5 0 1
5 1 0
6 0 0

I tried to look at combn() but I could not get this done with it.

Thank you in advance:
Daniel
#
probably expand.grid(), e.g.,

expand.grid(rep(list(0:6), 3))


I hope it helps.

Best,
Dimitris
On 4/21/2011 9:28 PM, 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.

daniel

2011-04-21 12:33 keltez?ssel, Dimitris Rizopoulos ?rta:
#
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.
#
Does the following do what you want?  It should
generate all the (unordered) NPart-partitions of Sum
by mapping the output of combn(Sum+NParts-1,NParts-1).  

f <- function (Sum, NParts) 
{
    cm <- combn(Sum + NParts - 1, NParts - 1)
    cm <- rbind(cm, Sum + NParts)
    if (NParts > 1) {
        r <- 2:NParts
        cm[r, ] <- cm[r, ] - cm[r - 1, ]
    }
    t(cm - 1)
}

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com