dimanche 12 février 2017

Generating binary matrix with number of 1's fixed within a range

How to generate a binary matrix with random number of 1s within a specific range, say between two to five, and at random positions?

I have tried matrix(sample(0:1, 10, replace = T), 5, 10), but I have no control of the number of 1s being generated.

Expected random output:

## 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




Aucun commentaire:

Enregistrer un commentaire