[R] combinations of m objects into r groups
Maria Montez
montez at bu.edu
Wed Dec 13 01:07:22 CET 2006
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
More information about the R-help
mailing list