[R] generating unordered combinations

Dan Halligan dan.halligan at gmail.com
Thu Sep 17 22:31:24 CEST 2009


Hi,

I am trying to generate all unordered combinations of a set of
numbers / characters, and I can only find a (very) clumsy way of doing
this using expand.grid.  For example, all unordered combinations of
the numbers 0, 1, 2 are:
0, 0, 0
0, 0, 1
0, 0, 2
0, 1, 1
0, 1, 2
0, 2, 2
1, 1, 1
1, 1, 2
1, 2, 2
2, 2, 2

(I have not included, for example, 1, 0, 0, since it is equivalent to
0, 0, 1).

I have found a way to generate this data.frame using expand.grid as
follows:

g <- expand.grid(c(0,1,2), c(0,1,2), c(0,1,2))
for(i in 1:nrow(g)) {
	g[i,] <- sort(as.character(g[i,]))
}
o <- order(g$Var1, g$Var2, g$Var3)
unique(g[o,]).

This is obviously quite clumsy and hard to generalise to a greater
number of characters, so I'm keen to find any other solutions.  Can
anyone suggest a better (more general, quicker) method?

Cheers




More information about the R-help mailing list