[R] generating unordered combinations
William Dunlap
wdunlap at tibco.com
Fri Sep 18 00:36:00 CEST 2009
There is a 1-1 correspondance between your n-sets
consisting of m possible element types (0 through m-1
in your example) and the number of n-subsets of a (n+m-1)-set.
E.g., your example had m=3 and n=3 and subtracting
1:3 from each column of combn(3+3-1,3) gives your result:
> t(combn(3+3-1, 3)-(1:3))
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 1
[3,] 0 0 2
[4,] 0 1 1
[5,] 0 1 2
[6,] 0 2 2
[7,] 1 1 1
[8,] 1 1 2
[9,] 1 2 2
[10,] 2 2 2
Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Dan Halligan
> Sent: Thursday, September 17, 2009 1:31 PM
> To: r-help at r-project.org
> Subject: [R] generating unordered combinations
>
> 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
>
> ______________________________________________
> R-help at r-project.org 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