[R] combinatorics

Charles C. Berry cberry at tajo.ucsd.edu
Fri Oct 13 20:02:12 CEST 2006


On Fri, 13 Oct 2006, Robin Hankin wrote:

> Hi
>
> How do I generate all ways of ordering  sets of indistinguishable items?
>
> suppose I have two A's, two B's and a C.
>
> Then I want
>
> AABBC
> AABCB
> AACBC
> ABABC
> . . .snip...
> BBAAC
> . . .snip...
> CBBAA
>
> [there are 5!/(2!*2!) = 30 arrangements.  Note AABBC != BBAAC]
>
> How do I do this?

I'd recursively use combn() to choose locations for A's, then B's, then 
...

> where.A <- combn(5,2)[, rep( 1:choose(5,2), each = choose(3,2)*choose(1,1))]
> where.not.A <- apply(where.A,2,function(x) (1:5)[-x])
> where.B <- matrix(apply(unique( where.not.A, MARGIN=2), 2, combn, 2 ),nr=2)
> where.not.AB <- apply(rbind(where.A,where.B),2,function(x) (1:5)[-x] )
> result <- matrix("C",nr=5,nc=30)
> result[ cbind( c( where.A ), c( col( where.A ) ) ) ] <- "A"
> result[ cbind( c( where.B ), c( col( where.B ) ) ) ] <- "B"
> cbind( apply(result,2,paste,collapse="") )
       [,1]
  [1,] "AABBC"
  [2,] "AABCB"
  [3,] "AACBB"
.
.
.


>
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
>  tel  023-8059-7743
>
> ______________________________________________
> 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.
>

Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717



More information about the R-help mailing list