Replace 0 with NA in R (Example) | Changing Zero in Data Frame & Vector


In this article, I’ll illustrate how to substitute 0 with NA in the R programming language.

The tutorial will contain this:

Let’s dive into it!


Creation of Example Data

We’ll use the following data frame for the example of this R programming tutorial:

data <- data.frame(x1 = c(2, 0, 7, 4, 0, 5),    # Create example data
                   x2 = c(0, 0, 0, 1, 1, 0))
data                                            # Print example data
# x1 x2
# 1  2  0
# 2  0  0
# 3  7  0
# 4  4  1
# 5  0  1
# 6  5  0

Our example data consists of six rows and two variables x1 and x2. Some of the values of these two rows are zero.


Example: Replace 0 with NA

Replacing 0 by NA in R is a simple task. We simply have to run the following R code:

data[data == 0] <- NA                           # Replace 0 with NA
data                                            # Print updated data
#   x1 x2
# 1  2 NA
# 2 NA NA
# 3  7 NA
# 4  4  1
# 5 NA  1
# 6  5 NA

As you can see based on the RStudio console output, we replaced all 0 values with NA values. Note that we could apply the same code to a vector or a single data frame column.


Video, Further Resources & Summary

Do you want to learn more about the manipulation of data in R? Then you could have a look at the following video of my YouTube channel. I show the R code of this tutorial in the video.


Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.


In addition, you might want to have a look at the other tutorials on You can find a selection of tutorials below:


This article explained how to change zeros in a data frame or vector to not available values in the R programming language. Tell me about it in the comments section, in case you have any further questions and/or comments.


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.