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.
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
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
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