
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create 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
Using 0:1
Using c(1,2) directly inside the function.
Also, we can set replace argument to TRUE or FALSE based on our requirement.
Examples
x1<-sample(0:1,size=50,replace=TRUE) x1
Output
[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
Example
x2<-sample(c(0,1),size=100,replace=TRUE) x2
Output
[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
Example
x3<-sample(c(0,1),size=150,replace=TRUE) x3
Output
[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
Example
x4<-sample(c(0,1),size=111,replace=TRUE) x4
Output
[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 0 1 0 0 1 0 1 [38] 0 0 0 1 0 0 1 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 [75] 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1
Example
x5<-sample(c(0,1),size=199,replace=TRUE) x5
Output
[1] 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1 [38] 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 [75] 0 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 0 0 0 1 0 1 1 1 1 0 1 1 1 0 0 0 0 1 0 1 1 [112] 1 0 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 1 1 1 1 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 0 [149] 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 [186] 1 1 1 1 0 0 0 1 1 1 0 0 0 1
Example
x6<-sample(c(0,1),size=5,replace=TRUE) x6
Output
[1] 0 1 1 1 0
Example
x7<-sample(c(0,1),size=49,replace=TRUE) x7
Output
[1] 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0 0 1 [39] 1 1 0 0 0 0 1 1 0 1 1
Example
x8<-sample(c(0,1),size=200,replace=TRUE) x8
Output
[1] 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 0 1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