Re: [R] combinatorics

From: Charles C. Berry <cberry_at_tajo.ucsd.edu>
Date: Fri 13 Oct 2006 - 18:02:12 GMT

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@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@tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717

______________________________________________
R-help@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. Received on Sat Oct 14 05:43:15 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 13 Oct 2006 - 20:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.