R, generate number vector only contains 0 and 1, with certain length
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