R How to Delete Data Frame Rows with At Least One Zero Value (Example Code)

In this R tutorial you’ll learn how to retain only rows that do not contain zeros.

Creation of Example Data

my_df <- data.frame(col1 = 6:0,                            # Constructing data
                    col2 = letters[7:1],
                    col3 = 0:6)
my_df                                                      # Returning data
#   col1 col2 col3
# 1    6    g    0
# 2    5    f    1
# 3    4    e    2
# 4    3    d    3
# 5    2    c    4
# 6    1    b    5
# 7    0    a    6

Example: Only Retain Data Frame Rows without Zeros

zero_rows <- apply(my_df, 1, function(row) all(row !=0 ))  # Logical zero indicator
zero_rows                                                  # Return logical indicator
# [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
my_df[zero_rows, ]                                         # Conditionally delete rows with zero
#   col1 col2 col3
# 2    5    f    1
# 3    4    e    2
# 4    3    d    3
# 5    2    c    4
# 6    1    b    5

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.
You need to agree with the terms to proceed

Menu
Top