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.
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.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you might have a look at the other articles of my website. I have published numerous posts already:
- Remove Duplicated Rows from Data Frame
- Conditionally Remove Row from Data Frame
- Remove Rows with NA from Data Frame
- Remove Empty Rows of Data Frame in R
- Introduction to R
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.
4 Comments. Leave new
Leave a Reply Cancel reply
Statistics Globe Newsletter
Very Useful and clear
Thank you very much Salar, glad you like it! 🙂
what if i have rows with 0.00 or 0.000 values, how do i specify?
cluster_removed[apply(cluster_removed, 1, function(row) all(row !=0.00)), ]
cluster_removed[apply(cluster_removed, 1, function(row) all(row !=0.000 )), ]
In this case, your column is not formatted as numeric. If your column contains only numbers, I would convert it to the numeric class as explained here: https://statisticsglobe.com/convert-character-to-numeric-in-r/