R, generates a numerical vector, contains only 0 and 1, with a certain length

I wanted to create a list / vector as follows:

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 the variable "X", and the position of 0 and 1 is completely random.

+4
source share
2 answers

Do you want to play with a selection with a replacement:

X <- 10; sample(c(0,1), replace=TRUE, size=X)
## [1] 1 1 0 0 0 0 0 1 0 1
+11
source
X <- rbinom(20, 1, 0.5)

This is a random binomial deviation function that will create a vector "X" of length 20 containing "0" and "1" with a success rate of 0.5. Here is the result.

> X
 [1] 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1
+8
source

All Articles