Remove Rows with Any Zero Value in R (Example)

 

In this tutorial, I’ll illustrate how to delete data frame rows where at least one value is equal to zero in the R programming language.

Table of contents:

Let’s dig in…

 

Creation of Exemplifying Data

Consider the following example data:

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

Have a look at the previous RStudio console output. It shows that our example data has six rows and four columns. Some of the variables of our example data contain zero values.

 

Example: Removing Rows with Zeros Using apply() & all() Functions

This example shows how to get rid of all rows with at least one zero value using the apply and all functions in R.

Have a look at the following R code:

data_zero <- data[apply(data, 1, function(row) all(row !=0 )), ]  # Remove zero-rows
data_zero                                                         # Print updated data
#   x1 x2 x3 x4
# 1  5  3  5  9
# 4  2  2  5  9
# 5  1  2  5  9

The previous R code returns our new data frame to the RStudio console. As you can see, all rows containing zeros were removed.

 

Video & Further Resources

If you need further explanations on the content of this post, you could watch the following video instruction of my YouTube channel. I’m explaining the R programming code of this tutorial in the video.

 

 

In addition, you might have a look at the other articles of my website. I have published numerous posts already:

 

In this tutorial you learned how to retain only rows that do not contain zeros in the R programming language. Let me know in the comments section, in case you have further 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.


4 Comments. Leave new

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.

Top