In R programming language, say you want to create a random binary vector with 4 elements.
The constraint is that the numbers of one's and zero's have to be equal.
So
(0,0,1,1)
(0,1,1,0)
(1,1,0,0)
...
Is there an easy way to do this?
Just randomly select every case without replacement from a set containing 2 0's and 2 1's.
sample(rep(0:1,each=2))
#[1] 0 1 1 0
Always works:
replicate(3,sample(rep(0:1,each=2)),simplify=FALSE)
#[[1]]
#[1] 1 0 0 1
#
#[[2]]
#[1] 0 1 0 1
#
#[[3]]
#[1] 1 1 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With