Roby
Roby

Reputation: 2061

get all Combinations of length N out of M

I'm searching for a simple way to get all possible unique combinations of the length N out of M.

Here a simple example:

M <- c( 1, 2, 3, 4, 5 )
N <- 2

Expected output:

1, 2
1, 3 
1, 4
1, 5
2, 3
2, 4
2, 5
3, 4
3, 5
4, 5

Upvotes: 2

Views: 271

Answers (2)

dardisco
dardisco

Reputation: 5274

This gives the same result as @jdharrison's example.

combnPrim is quite a bit faster as rapidly hands over to .C, although clearly this is overkill for an example where only one small combination is required.

library(gRbase)
### the following dependencies may be necessary, install as follows:
### source("http://bioconductor.org/biocLite.R")
### biocLite("graph")
### biocLite("BiocGenerics")
### biocLite("RBGL")
gRbase::combnPrim(seq(5), 2)

Upvotes: 0

jdharrison
jdharrison

Reputation: 30455

Use the combn function

> n <- 1:5
> combn(n, 2)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    2    2    2    3    3     4
[2,]    2    3    4    5    3    4    5    4    5     5

Upvotes: 6

Related Questions