How to convert binary variable to 0/1 format in an R data frame?


A binary variable is a type of variable that can take only two possible values like gender that has two categories male and female, citizenship of a country with two categories as yes and no, etc. If the binary variable is not in 0/1 format then it can be converted with the help of ifelse function. Check out the below examples to understand how it works.

Consider the below data frame −

Example

 Live Demo

Temp<-sample(c("Hot","Cold"),20,replace=TRUE)
Response<-rnorm(20,25,3.2)
df1<-data.frame(Temp,Response)
df1

Output

   Temp  Response
1  Cold   26.02542
2  Cold   22.39046
3  Hot    24.84536
4  Cold   25.64836
5  Hot    28.29392
6  Cold   27.58198
7  Hot    23.77825
8  Cold   30.17105
9  Cold   27.08661
10 Cold   36.36730
11 Hot    24.73742
12 Cold   23.43371
13 Hot    23.72180
14 Cold   19.81232
15 Hot    24.45042
16 Cold   30.39320
17 Cold   21.23361
18 Hot    25.21617
19 Cold   23.20461
20 Cold   25.22150

Converting Temp column of df1 to 0/1 format −

Example

df1$Temp<-ifelse(df1$Temp=="Cold",1,0)
df1

Output

   Temp Response
1  1    26.02542
2  1    22.39046
3  0    24.84536
4  1    25.64836
5  0    28.29392
6  1    27.58198
7  0    23.77825
8  1    30.17105
9  1    27.08661
10 1    36.36730
11 0    24.73742
12 1    23.43371
13 0    23.72180
14 1    19.81232
15 0    24.45042
16 1    30.39320
17 1    21.23361
18 0    25.21617
19 1    23.20461
20 1    25.22150

Updated on: 10-Feb-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements