[R] Getting all possible combinations

Bert Gunter bgunter.4567 at gmail.com
Wed Aug 23 17:51:49 CEST 2017


Please at least do a basic internet search before posting here.
Searching on "R combinations" brought up the combn() function, which
you can use in a simple loop to get your answer:

> lapply(seq_len(5), FUN = function(x)combn(LETTERS[1:5], x))
## You can use a for() loop if you prefer

[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,] "A"  "B"  "C"  "D"  "E"

[[2]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "A"  "A"  "A"  "A"  "B"  "B"  "B"  "C"  "C"  "D"
[2,] "B"  "C"  "D"  "E"  "C"  "D"  "E"  "D"  "E"  "E"

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "A"  "A"  "A"  "A"  "A"  "A"  "B"  "B"  "B"  "C"
[2,] "B"  "B"  "B"  "C"  "C"  "D"  "C"  "C"  "D"  "D"
[3,] "C"  "D"  "E"  "D"  "E"  "E"  "D"  "E"  "E"  "E"

[[4]]
     [,1] [,2] [,3] [,4] [,5]
[1,] "A"  "A"  "A"  "A"  "B"
[2,] "B"  "B"  "B"  "C"  "C"
[3,] "C"  "C"  "D"  "D"  "D"
[4,] "D"  "E"  "E"  "E"  "E"

[[5]]
     [,1]
[1,] "A"
[2,] "B"
[3,] "C"
[4,] "D"
[5,] "E"



Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Wed, Aug 23, 2017 at 8:33 AM, Christofer Bogaso
<bogaso.christofer at gmail.com> wrote:
> Hi again,
>
> I am exploring if R can help me to get all possible combinations of
> members in a group.
>
> Let say I have a group with 5 members : A, B, C, D, E
>
> Now I want to generate all possible unique combinations with all
> possible lengths from that group e.g.
>
> 1st combination : A
> 2nd combination : B
> .....
> 5th combination : E
> 6th combination : A, B
> 7th combination : B, C
> ....
> last combination: A, B, C, D, E
>
> Ideally, I have a fairly large group so am looking for some
> programmatic way to generate all possible combinations.
>
> Any help will be highly appreciated.
>
> Thanks for your time.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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