[R] combinatorics again

Robin Hankin r.hankin at noc.soton.ac.uk
Mon Mar 6 10:21:05 CET 2006


Thank you Jacques

but your solution  misses (eg) c(1,1,2) which I need.

best wishes

Robin



On 6 Mar 2006, at 09:17, Jacques VESLOT wrote:

> > library(gtools)
> > combinations(5,3)
>      [,1] [,2] [,3]
> [1,]    1    2    3
> [2,]    1    2    4
> [3,]    1    2    5
> [4,]    1    3    4
> [5,]    1    3    5
> [6,]    1    4    5
> [7,]    2    3    4
> [8,]    2    3    5
> [9,]    2    4    5
> [10,]    3    4    5
>
>
> Robin Hankin a écrit :
>
>> Hi
>>
>> I want to enumerate all vectors of length "J", whose elements are
>> integers in the range 1 to S, without regard to ordering.
>>
>> With J=S=3, the combinations are as follows:
>>
>>
>>        [,1] [,2] [,3]
>>  [1,]    1    1    1
>>  [2,]    1    1    2
>>  [3,]    1    1    3
>>  [4,]    1    2    2
>>  [5,]    1    2    3
>>  [6,]    1    3    3
>>  [7,]    2    2    2
>>  [8,]    2    2    3
>>  [9,]    2    3    3
>> [10,]    3    3    3
>>
>>
>> Note that (eg) c(1,2,1) is not on the list because we already have
>> c(1,1,2) which would be equivalent [because the problem is to
>> enumerate the cases without regard to ordering] and I do not want
>> repeats.
>>
>> The best I can do is to create all S^J possibilities and weed out the
>> repeats, using unique() ; code below.
>>
>> Why is this no good?  Well, even for the tiny case of J=S=10, this
>> would require a matrix of 10^10 rows, and my little linux machine
>> refuses to cooperate, complaining about allocating a vector of
>> length 1410065408.  For these values of J and S, I happen to know
>> that the are 6360 distinct combinations, which is eminently  
>> handleable.
>>
>>
>> Anyone got any better ideas?
>>
>>
>>
>>
>>
>>
>> allcomb <- function(J,S){
>>
>>   f <- function(...) {
>>     1:S
>>   }
>>   out <- as.matrix(do.call("expand.grid", lapply(1:J, FUN = f)))
>>   out <- t(apply(out,1,sort))
>>   unique(out)
>> }
>>
>>
>> --
>> 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
>>
>>

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743




More information about the R-help mailing list