生成数量为1的二进制矩阵,其固定在一个范围内

时间:2017-02-13 02:29:19

标签: r matrix random

如何在特定范围内生成随机数为1s的二进制矩阵,比如在2到5之间,以及随机位置?

我尝试了matrix(sample(0:1, 10, replace = T), 5, 10),但我无法控制正在生成1s的数量。

预期的随机输出:

## each row has number of 1s in range(2,5)

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    1    1    0    0    0    0    0    1     0     ## four 1s at row 1
 [2,]    0    0    0    1    1    0    0    0    0     1     ## three 1s at row 2
 [3,]    0    0    0    0    1    0    0    1    0     0     ## two 1s at row 3
 [4,]    1    1    1    0    0    0    1    0    0     1     ## five 1s at row 4
 [5,]    0    1    0    1    0    1    0    1    0     0     ## four 1s at row 5

0 个答案:

没有答案