# How to generate a vector of 0 and 1 in R

I want to generate a vector containing only 0 and 1 randomly. Which R function should I use for it?

e.g. (0,1,0,0,1,1,0,1)

+1 vote
by (48.7k points)
edited by

R function sample() can be used to generate a vector of 0 and 1 only. It generates random samples from the given vector of one or more elements or a positive integer.

In the following example, I am generating a vector of size 10. The parameter can be specified using either "c()" or ":".

> a <- sample(c(0,1), size = 10, replace = TRUE)
> a
[1] 1 1 0 0 1 1 1 1 0 0
> a <- sample(0:1, size = 10, replace = TRUE)
> a
[1] 1 0 1 0 0 1 0 1 1 0

You can also use the R function rbinom(). First, generate a list of probabilities using runif() function and then use those probabilities as a parameter in rbinorm() to get random samples from a binomial distribution.

Here is an example of generating a vector of size 10:

> p = runif(n=10)
> rbinom(length(p), prob = p, size = 1)
[1] 1 0 0 1 0 0 1 1 1 0