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

+2 votes

Best answer

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