Generate Vectors only Contains 0 And 1 in R

You can generate a vector only containing 0 and 1 in R using sample() and rbinom() functions.

sample:

sample(c(0, 1), size = 10, replace = TRUE)

rbinom:

rbinom(10, size = 1, prob = 0.5)

In both sample() and rbinom():

  • size: The number of elements to generate in the vector.
  • replace: A logical value indicating whether the elements in the vector can be repeated.
  • prob: The probability of generating a 1.

Example 1


# use sample() to generate 10 numbers, either 1 or 0
vector_1<-sample(c(0, 1), size = 10, replace = TRUE) 


# print out the vector
print(vector_1)

The following is the output.

> print(vector_1)
 [1] 0 0 1 1 1 1 0 1 0 1

Example 2

# use sample() to generate 10 numbers, either 1 or 0
vector_2<-rbinom(10, size = 1, prob = 0.5) 

# print out the vector
print(vector_2)

The following is the output.

> print(vector_2)
 [1] 1 0 1 0 1 1 0 1 0 0

Reference

The following is another tutorial on how go generate number vectors only containing 0 an 1 in R.

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

Leave a Comment