Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random binary vector with equal Ones and Zeros

Tags:

random

r

vector

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?

like image 698
Juergen Avatar asked Dec 07 '25 09:12

Juergen


1 Answers

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
like image 107
thelatemail Avatar answered Dec 09 '25 22:12

thelatemail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!