Change Yes to 1 & No to 0 in R (Example)


In this tutorial you’ll learn how to convert Yes to 1 and No to 0 in R.

Table of contents:

Let’s dig in:


Creating Example Data

We’ll use the following data as basement for this R tutorial:

vec <- c("Yes", "No", "No", "Yes", "No")
# [1] "Yes" "No"  "No"  "Yes" "No"

As you can see based on the previous output of the RStudio console, our example data is a character vector containing the character string “Yes” and “No” multiple times.


Example: Conditionally Change “Yes” to 1 & “No” to 0

This example illustrates how to convert and relabel a vector from Yes and No to 1 and 0 (i.e. a dummy variable).

First, we should duplicate our input vector to keep an original version of our data:

vec_dummy <- vec                        # Duplicate vector

Next, we should make sure that our vector has the character class. In the present example, this is already the case. However, it cannot hurt to apply the as.character function to our data to make sure that we are dealing with character strings:

vec_dummy <- as.character(vec_dummy)    # Convert vector to character

In the next step, the replacement takes place. We are using a logical condition to change each Yes to a 1 and each No to a 0:

vec_dummy[vec_dummy == "Yes"] <- 1      # Replace "Yes" by 1
vec_dummy[vec_dummy == "No"] <- 0       # Replace "No" by 0

At this point, our vector contains the values 1 and 0 formatted as characters. We can convert this vector to the numeric class using the as.numeric function:

vec_dummy <- as.numeric(vec_dummy)      # Convert vector to numeric

Finally, we can print our new vector containing only 1 and 0 to the RStudio console:

vec_dummy                               # Print updated vector
# [1] 1 0 0 1 0

Looks great!

Please note that we could have applied the same code to substitute a data frame column, or even to multiple data frame columns. However, for the sake of simplicity, I have only used a vector object in this tutorial.


Video, Further Resources & Summary

In case you need further information on the R codes of this tutorial, you might want to watch the following video on my YouTube channel. I show the content of this tutorial in the video:



Furthermore, you might read some of the related tutorials on my website. I have released several articles already:


Summary: At this point you should have learned how to change and modify Yes to 1 and No to 0 in the R programming language. Let me know in the comments below, if you have additional questions.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.