3

如果例如 |S| = 8,我怎样才能得到具有以下形式的行的 256 x 8 矩阵:

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

3 回答 3

3

也许这有帮助:

library(e1071)
bincombinations(8)
于 2012-12-15T12:05:04.790 回答
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输出一个数字矩阵,恕我直言,这是糟糕的设计。

于 2012-12-15T14:00:03.743 回答
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)))
于 2012-12-15T11:23:57.447 回答