- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change the code "Yes" to 1 in an R data frame column?
To change the code “Yes” to 1, we can use ifelse function and set the Yes to 1 and others to 0. For example, if we have a data frame called df that contains a character column x which has Yes and No values then we can convert those values to 1 and 0 using the command ifelse(df$x=="Yes",1,0).
Example1
Consider the below data frame −
Agree<-sample(c("Yes","No"),20,replace=TRUE) x<-rpois(20,5) df1<-data.frame(Agree,x) df1
Output
Agree x 1 No 6 2 No 4 3 Yes 5 4 No 9 5 No 4 6 No 0 7 Yes 4 8 No 5 9 No 6 10 No 5 11 No 6 12 No 2 13 No 6 14 No 2 15 Yes 3 16 Yes 9 17 No 3 18 Yes 3 19 No 0 20 Yes 7
Converting Yes to 1 and No to 0 in df1 −
df1$Agree<-ifelse(df1$Agree=="Yes",1,0) df1
Agree x 1 0 6 2 0 4 3 1 5 4 0 9 5 0 4 6 0 0 7 1 4 8 0 5 9 0 6 10 0 5 11 0 6 12 0 2 13 0 6 14 0 2 15 1 3 16 1 9 17 0 3 18 1 3 19 0 0 20 1 7
Example2
Approved<-sample(c("Yes","No"),20,replace=TRUE) y<-rnorm(20,30,2.4) df2<-data.frame(Approved,y) df2
Output
Approved y 1 Yes 33.17910 2 No 31.69268 3 Yes 30.96484 4 Yes 34.12339 5 Yes 30.84079 6 No 27.57933 7 Yes 29.13050 8 No 32.55457 9 Yes 34.39399 10 No 30.22306 11 Yes 29.65322 12 Yes 29.42060 13 Yes 30.75312 14 No 32.25545 15 Yes 27.54001 16 No 25.93290 17 No 27.45960 18 Yes 26.28884 19 No 32.08387 20 Yes 28.60269
Converting Yes to 1 and No to 0 in df2 −
df2$Approved<-ifelse(df2$Approved=="Yes",1,0) df2
Approved y 1 1 33.17910 2 0 31.69268 3 1 30.96484 4 1 34.12339 5 1 30.84079 6 0 27.57933 7 1 29.13050 8 0 32.55457 9 1 34.39399 10 0 30.22306 11 1 29.65322 12 1 29.42060 13 1 30.75312 14 0 32.25545 15 1 27.54001 16 0 25.93290 17 0 27.45960 18 1 26.28884 19 0 32.08387 20 1 28.60269
Advertisements