你可以試試這個方法:
f <- function(n=5,m=3)
t(apply(combn(1:n,m=m),2,function(cm) replace(rep(0,n),cm,1)))
f(5,3)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 1 1 0 0
# [2,] 1 1 0 1 0
# [3,] 1 1 0 0 1
# [4,] 1 0 1 1 0
# [5,] 1 0 1 0 1
# [6,] 1 0 0 1 1
# [7,] 0 1 1 1 0
# [8,] 0 1 1 0 1
# [9,] 0 1 0 1 1
# [10,] 0 0 1 1 1
的想法是生成指數的所有組合爲1,然後到u讓他們產生最終結果。
相同方法的另一個味:
f.2 <- function(n=5,m=3)
t(combn(1:n,m,FUN=function(cm) replace(rep(0,n),cm,1)))
第二種方法是約兩倍快:
library(rbenchmark)
benchmark(f(16,8),f.2(16,8))
# test replications elapsed relative user.self sys.self user.child sys.child
# 2 f.2(16, 8) 100 5.706 1.000 5.688 0.017 0 0
# 1 f(16, 8) 100 10.802 1.893 10.715 0.082 0 0
基準
f.akrun <- function(n=5,m=3) {
indx <- combnPrim(1:n,m)
DT <- setDT(as.data.frame(matrix(0, ncol(indx),n)))
for(i in seq_len(nrow(DT))){
set(DT, i=i, j=indx[,i],value=1)
}
DT
}
benchmark(f(16,8),f.2(16,8),f.akrun(16,8))
# test replications elapsed relative user.self sys.self user.child sys.child
# 2 f.2(16, 8) 100 5.464 1.097 5.435 0.028 0 0
# 3 f.akrun(16, 8) 100 4.979 1.000 4.938 0.037 0 0
# 1 f(16, 8) 100 10.854 2.180 10.689 0.129 0 0
@ akrun的溶液(f.akrun
)的〜10 %比f.2
快。
[編輯] 另一種方法,這更加快速和簡單的:
f.3 <- function(n=5,m=3) t(combn(n,m,tabulate,nbins=n))
一個不那麼有效的方法將是'X < - expand.grid(REP(列表(0L:1L),5L)); x [rowSums(x)== 3L,]'但我認爲你想要比這更快的東西。 – 2015-02-06 14:43:47
以下可能有所幫助:http://stackoverflow.com/questions/17292091/rbinary-matrix-for-all-possible-unique-results – 2015-02-06 14:45:01