2014-06-05 58 views
1

我在尋找一個簡單的方法來獲得的長度爲N的所有可能的唯一組合出M.得到的長度爲N的所有組合M個

一個簡單的例子

這裏:

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

預期成果:

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

你是什麼谷歌'combn'沒有馬上出來? – MrFlick

+0

請注意'combn'返回所有組合'沒有替換',這是你所要求的。 'expand.grid'返回所有組合'替換':'expand.grid(x1 = c(1:5),x2 = c(1:5))''。我不知道'combn'是否可以返回所有組合'替換'。 –

回答

6

使用combn功能

> 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 
0

這給出了與@ jdharrison的例子相同的結果。

combnPrim比快速交給.C要快得多,雖然很明顯這是一個矯枉過正的例子,只需要一個小組合。

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) 
相關問題