Juergen
Juergen

Reputation: 3743

Generate random binary vector with equal Ones and Zeros

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?

Upvotes: 3

Views: 6207

Answers (3)

Eric Leschinski
Eric Leschinski

Reputation: 154103

Create a random binary vector with random ones 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);

Prints:

[1] 0 1 1 0

Upvotes: 0

npjc
npjc

Reputation: 4194

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

or generalise to:

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

Upvotes: 2

thelatemail
thelatemail

Reputation: 93938

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

Upvotes: 7

Related Questions