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
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:
- 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.