Generate random binary vector with equal ones and zeros

In the R programming language, let's say you want to create a random binary vector with 4 elements.

The limitation is that the numbers one and zero must be equal.

So,

(0,0,1,1)
(0,1,1,0)
(1,1,0,0)
...

      

Is there an easy way to do this?

+3


source to share


3 answers


Just randomly select each case without replacement from a set containing 2 0 and 2 1.

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

      

+6


source


sample(c(1,1,0,0), 4)

      

or generalize to:



sample(rep(c(0,1),length.out=n/2),n)

      

+2


source


Create a random binary vector with random and zeros:

#create a binary vector:
result <- vector(mode="logical", length=4);

#loop over all the items:
for(i in 1:4){
    #for each item, replace it with 0 or 1
    result[i] = sample(0:1, 1);
}
print(result);

      

Printing

[1] 0 1 1 0

      

0


source







All Articles