创建二进制矢量的组合 [英] Create combinations of a binary vector
问题描述
我想创建由固定数量的0和1。例如二元载体的所有可能的组合:
暗淡(V)= 5X1; N1 = 3; N0 = 2;
在这种情况下,我想有这样的:
I would like to create all possible combinations of a binary vector made of a fixed number of 0 and 1. For example: dim(v)=5x1; n1=3; n0=2; In this case I'd like to have something like:
1,1,1,0,0
1,1,0,1,0
1,1,0,0,1
1,0,1,1,0
1,0,1,0,1
1,0,0,1,1
0,1,1,1,0
0,1,1,0,1
0,1,0,1,1
0,0,1,1,1
我发现了一些帮助阅读这篇文章
<一href=\"http://stackoverflow.com/questions/27826508/create-all-possible-combiations-of-0-1-or-2-1s-of-a-binary-vector-of-length-n\">Create的0,1,或2英寸的所有可能combiations 1 QUOT氏长度为n 的二元载体的
但我想生成只需要我避免空间浪费任何组合(我认为这个问题将有n explonentially增加)
I found some help reading this post Create all possible combiations of 0,1, or 2 "1"s of a binary vector of length n but i would like to generate only the combinations I need avoiding any waste of space (I think that the problem will increase explonentially with n)
推荐答案
萨芬的回答稍微更快的版本:
A slightly faster version of Marat's answer:
f.roland <- function(n, m) {
ind <- combn(seq_len(n), m)
ind <- t(ind) + (seq_len(ncol(ind)) - 1) * n
res <- rep(0, nrow(ind) * n)
res[ind] <- 1
matrix(res, ncol = n, nrow = nrow(ind), byrow = TRUE)
}
all.equal(f.2(16, 8), f.roland(16, 8))
#[1] TRUE
library(rbenchmark)
benchmark(f(16,8),f.2(16,8),f.roland(16,8))
# test replications elapsed relative user.self sys.self user.child sys.child
#2 f.2(16, 8) 100 5.693 1.931 5.670 0.020 0 0
#3 f.roland(16, 8) 100 2.948 1.000 2.929 0.017 0 0
#1 f(16, 8) 100 8.287 2.811 8.214 0.066 0 0
这篇关于创建二进制矢量的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!