21

I wanted to create a list/vector like this:

c(0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1)

or

c(0,0,1,0,1,0,1,1,1,1,0,1,0,1,1,0,1)

the length of this vector is a variable 'X', and the position of 0 and 1 are totally random.

2 Answers 2

34
X <- rbinom(20, 1, 0.5)

It is a random binomial deviate generator function which will create a vector 'X' of length 20 containing '0' and '1' with success probability of 0.5. Here is the output.

> X
 [1] 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1
0
27

This can be done via sampling with replacement from the set of binary digits:

n <- 10 # sample size
sample(c(0,1), replace=TRUE, size=n)

On a side note, if you wish - for whatever reason - to reproduce exactly the two above vectors, you will need to change the random number generator's seed:

set.seed(194842)
sample(c(0,1), replace=TRUE, size=21)
## [1] 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

set.seed(153291)
sample(c(0,1), replace=TRUE, size=17)
## [1] 0 0 1 0 1 0 1 1 1 1 0 1 0 1 1 0 1
2
  • 7
    A little trick. You can also write sample(2)-1 so that you don't have to write c(0,1) in sample. I think it's also a bit faster Commented Oct 1, 2014 at 9:17
  • If size is big then it will not be faster because -1 will result in extra allocation an a loop. Also there is sample.int if one wants speed.
    – jangorecki
    Commented May 31, 2020 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.