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
我在尋找一個簡單的方法來獲得的長度爲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
使用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
這給出了與@ 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)
你是什麼谷歌'combn'沒有馬上出來? – MrFlick
請注意'combn'返回所有組合'沒有替換',這是你所要求的。 'expand.grid'返回所有組合'替換':'expand.grid(x1 = c(1:5),x2 = c(1:5))''。我不知道'combn'是否可以返回所有組合'替換'。 –