How to Convert Yes to 1 & No to 0 in R (Example Code)

This tutorial demonstrates how to switch from Yes to 1 and No to 0 in the R programming language.

Creation of Example Data

x <- factor(c("No", "No", "Yes", "No", "Yes", "Yes", "No"))
x
# [1] No  No  Yes No  Yes Yes No 
# Levels: No Yes

Example: How to Switch from “Yes” to 1 & “No” to 0

x_new <- x                      # Replicating vector
x_new <- as.character(x_new)    # Converting factor to character
x_new[x_new == "Yes"] <- 1      # Replacing Yes by 1
x_new[x_new == "No"] <- 0       # Replacing No by 0
x_new <- as.numeric(x_new)      # Converting character to numeric
x_new                           # Displaying new data
# [1] 0 0 1 0 1 1 0

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top