How to create a random sample with values 0 and 1 in R?

It is known that the random sample can be created by using sample function in R. If we want to create a random sample with values 0 and 1 only then there are three different ways to pass them inside the sample function −
Creating a vector of 0 and 1
Creating a vector of 0 and 1
Using 0:1
Using 0:1
Using c(1,2) directly inside the function.
Using c(1,2) directly inside the function.
Also, we can set replace argument to TRUE or FALSE based on our requirement.
 Live Demo
x1<-sample(0:1,size=50,replace=TRUE)
x1
[1] 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 0 1 0 1 1 0 1 1
[39] 0 0 0 0 0 1 1 1 0 1 1 1
 Live Demo
x2<-sample(c(0,1),size=100,replace=TRUE)
x2
[1] 0 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 0 1 0 0 1
[38] 1 1 0 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0
[75] 0 0 1 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0
 Live Demo
x3<-sample(c(0,1),size=150,replace=TRUE)
x3
[1] 0 1 1 0 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 0 0 0 1 1 1 1 0 1 0 1 1 1 1 1 0
[38] 1 1 0 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 1 1 0 1 0
[75] 1 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 0 0 0 0 1 0 1 0 0
[112] 1 0 0 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 1 1 1 0 1 0 0 0
[149] 1 1
 Live Demo
x4<-sample(c(0,1),size=111,replace=TRUE)
x4
[1] 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1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