生成powerset作为0/1选择向量的列表

时间:2012-12-15 11:05:22

标签: r

如果是| S | = 8,如何获得具有以下形式行的256 x 8矩阵:

> sample(c(0,1),8,replace=T)
[1] 1 0 0 1 1 1 0 0

3 个答案:

答案 0 :(得分:3)

也许这会有所帮助:

library(e1071)
bincombinations(8)

答案 1 :(得分:2)

这是bincombinations

的更快(并且可以更清晰)的版本
fast.bincombinations <- function(p)
    vapply(X = seq_len(p),
           FUN = function(i)rep(rep(0:1, each = 2^(p-i)), times = 2^(i-1)),
           FUN.VALUE = integer(2^(p)))

system.time(fast.bincombinations(24))
#    user  system elapsed 
#   2.967   1.056   3.995 

system.time(bincombinations(24))
#    user  system elapsed 
#  11.144  12.111  53.687

我们还要提到bincombinations输出一个数字矩阵,这是糟糕的设计恕我直言。

答案 2 :(得分:1)

你可以这样做:

s = 8                                        # <-- |s| = 8
pset <- t(sapply(0:(2^s-1),intToBits))[,1:s] # <-- a matrix of 256x8 raws
pset <- apply(pset ,2,as.integer)            # <-- raws to integers

结果:

> head(pset)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    0    0    0    0    0    0    0
[2,]    1    0    0    0    0    0    0    0
[3,]    0    1    0    0    0    0    0    0
[4,]    1    1    0    0    0    0    0    0
[5,]    0    0    1    0    0    0    0    0
[6,]    1    0    1    0    0    0    0    0
> tail(pset)
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[251,]    0    1    0    1    1    1    1    1
[252,]    1    1    0    1    1    1    1    1
[253,]    0    0    1    1    1    1    1    1
[254,]    1    0    1    1    1    1    1    1
[255,]    0    1    1    1    1    1    1    1
[256,]    1    1    1    1    1    1    1    1

这是另一种方式:

s = 8;
res <- sapply(0:(s-1),function(x)rep(c(rep(0,2^x),rep(1,2^x)),2^(s-x-1)))