[R] combinations of m objects into r groups

Bert Gunter gunter.berton at gene.com
Wed Dec 13 01:35:35 CET 2006


This issue has come up before:

RSiteSearch("nkpartitions") 

will find references for you on CRAN.

You might also try
http://ranau.cs.ui.ac.id/book/AlgDesignManual/BOOK/BOOK4/NODE153.HTM

for some background, or google on "set partitions".

Bottom line: it ain't trivial.

Cheers,

Bert Gunter
Genentech Nonclinical Statistics
South San Francisco, CA 94404

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Maria Montez
Sent: Tuesday, December 12, 2006 4:07 PM
To: r-help at stat.math.ethz.ch
Subject: [R] combinations of m objects into r groups

Hi!

Suppose I have m objects. I need to find out what are all possible ways 
I can group those m objects into r groups. Moreover, I need to create a 
matrix that contains what those arrangements are. I've created code for 
when r=2 but I've come to a halt when trying to generalize it into r groups.

For example, if I have m=6 objects and I want to arrange them into 
groups of r=2, there are a total of 41 possible arrangements. I would 
like a matrix of the form (showing only 9 possible arrangements):

  c1 c2 c3 c4 c5 c6 c7 c8 c9
1  1  2  2  2  2  2  1  1  1
2  2  1  2  2  2  2  1  2  2
3  2  2  1  2  2  2  2  1  2
4  2  2  2  1  2  2  2  2  1
5  2  2  2  2  1  2  2  2  2
6  2  2  2  2  2  1  2  2  2

This means that arrangement c1 puts object 1 into group 1 and all other 
objects into group 2.

I've created code for this particular example with two groups. I'm using 
the subsets function which I've found posted online, in a post that 
references page 149 of Venables and Ripley (2nd ed).

#subsets function computes all possibles combinations of n objects r at a
time 
subsets<-function(r,n,v=1:n)
{
        if(r<=0) NULL else
        if(r>=n) v[1:n] else
        rbind(cbind(v[1],Recall(r-1,n-1,v[-1])), Recall(r, n-1,v[-1]))
}
#labels for objects
r <- c("1100","1010","1001","0110","0101","0011")
m<-length(r)
for (k in 1:trunc(m/2)){
  a <- subsets(k, m)
  for (i in 1:dim(a)[1]){
    sub <- rep(2, m)
    b <- a[i,]
    for (j in 1:length(b)){
      sub[b[j]]=1
    }
    r <- data.frame(r, sub)
  }
}
names <- c("xcomb")
for (i in 1:(dim(r)[2]-1)) {
  names <- c(names,paste("c",i,sep=""))
}
names(r) <- names

Any suggestions?

Thanks, Maria








After searching for help I found a

______________________________________________
R-help at stat.math.ethz.ch 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.



More information about the R-help mailing list