生成固定数为1的二进制矩阵

时间:2017-02-01 04:17:00

标签: r matrix random

如何生成具有以下行为的二进制矩阵?我遇到过这个solution,但它没有二进制值的随机定位。

## all rows contain four 1's at random column

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    1    1    0    0    0    0    0    1     0
 [2,]    0    0    0    1    1    1    0    0    0     1
 [3,]    0    0    0    1    1    0    0    1    1     0
 [4,]    0    1    1    0    0    0    1    0    0     1
 [5,]    0    1    0    1    0    1    0    1    0     0

1 个答案:

答案 0 :(得分:1)

这可能没有优化,但会让你前进:

m<-matrix(data = rep(sample(rep(c(1,0),times=c(4,6))),times=5),byrow = T,nrow = 5,ncol = 10)
m<-apply(X = m,FUN = sample,MARGIN = 1)
m<-t(m)