[R] Combinatorial problem

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Aug 12 13:47:34 CEST 2009


you could try something like the following:

groups <- list(gp1 = 1:3, gp2 = 4:5, gp3 = 6:7,
                gp4 = 8:10, gp5 = 11)

combn(5, 2, function (x) expand.grid(groups[x]), simplify = FALSE)
combn(5, 3, function (x) expand.grid(groups[x]), simplify = FALSE)
combn(5, 4, function (x) expand.grid(groups[x]), simplify = FALSE)


I hope it helps.

Best,
Dimitris


David Scott wrote:
> I have been struggling trying to write some code to produce all 
> combinations subject to some restrictions. I thought someone might have 
> some bright ideas.
> 
> I have 11 values which fall into 5 groups. I want all combinations of 
> 2,3, and 4 values where each value must be from a different group. The 
> numbers in the groups are different. Here is a definition of the groups:
> 
> groups <- list(gp1 = 1:3, gp2 = 4:5, gp3 = 6:7,
>                gp4 = 8:10, gp5 = 11)
> 
> I don't need the problem to be generalized at all---I just want to solve 
> this problem.
> 
> My approach so far has been to use combinations() from gtools to select 
> the combinations of groups and then to try and expand from there. I am 
> nearly there I think but it seems excessively complicated. I can 
> definitely do the all combinations of 2 from 11 subject to the group 
> restriction.
> 
> Suggestions are most welcome.
> 
> David Scott
> 
> _________________________________________________________________
> David Scott    Department of Statistics
>         The University of Auckland, PB 92019
>         Auckland 1142,    NEW ZEALAND
> Phone: +64 9 923 5055, or +64 9 373 7599 ext 85055
> Email:    d.scott at auckland.ac.nz,  Fax: +64 9 373 7018
> 
> Director of Consulting, Department of Statistics
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list