I've had to do something similar, so I wrote a small function to help.
This runs in about 1/4 the time of your code on my machine.
Others may have a more efficient approach.

all.combs <- function(num, from=0, to=num) {
        # create a matrix of all possible combinations of num items
        # restrict each row to have between "from" and "to" items 
        res <- vector("list", to-from+1)
        for(i in seq(from:to)) {
                j <- (from:to)[i]
                if(j==0) res[[i]] <- rep(FALSE, num)
                comb <- combn(num, j)
                res[[i]] <- t(apply(comb, 2, function(x) 
!is.na(match(1:num, x))))
                }
        do.call(rbind, res)
        }

all.combs(20, 5, 13)

Jean


wwreith <reith_william@bah.com> wrote on 07/20/2012 07:45:30 AM:

> General problem: I have 20 projects that can be invested in and I need 
to
> decide which combinations meet a certain set of standards. The total
> possible combinations comes out to 2^20. However I know for a fact that 
the
> number of projects must be greater than 5 and less than 13. So far the 
the
> code below is the best I can come up with for iteratively creating a set 
to
> check against my set of standards.
> 
> Code
> x<-matrix(0,nrow=1,ncol=20)
> for(i in 1:2^20)
> {
> x[1]<-x[1]+1
>   for(j in 1:20)
>   {
>     if(x[j]>1)
>     {
>       x[j]=0
>       if(j<20)
>       {
>         x[j+1]=x[j+1]+1
>       }
>     }
>   }
> if(sum(x)>5 && sum(x)<13)
> {
> # insert criteria here.
> }
> }
> 
> my code forces me to create all 2^20 x's and then use an if statement to
> decide if x is within my range of projects. Is there a faster way to
> increment x. Any ideas on how to kill the for loop so that it won't 
attempt
> to process an x where the sum is greater than 12 or less than 6?

	[[alternative HTML version deleted]]

