Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, generate number vector only contains 0 and 1, with certain length

Tags:

r

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.

like image 465
Xiangwu Avatar asked Oct 01 '14 08:10

Xiangwu


2 Answers

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
like image 135
gagolews Avatar answered Oct 01 '22 04:10

gagolews


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
like image 30
cropgen Avatar answered Oct 01 '22 04:10

cropgen