How to Remove Rows with Any Zeros in R (With Example)


You can use one of the following methods to remove rows with any zeros in a data frame in R:

Method 1: Remove Rows with Any Zeros Using Base R

df_new <- df[apply(df!=0, 1, all),]

Method 2: Remove Rows with Any Zeros Using dplyr

library(dplyr)

df_new <- filter_if(df, is.numeric, all_vars((.) != 0))

The following examples show how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(points=c(5, 7, 8, 0, 12, 14, 0, 10, 8),
                 assists=c(0, 2, 2, 4, 4, 3, 7, 6, 10),
                 rebounds=c(8, 8, 7, 3, 6, 5, 0, 12, 11))

#view data frame
df

  points assists rebounds
1      5       0        8
2      7       2        8
3      8       2        7
4      0       4        3
5     12       4        6
6     14       3        5
7      0       7        0
8     10       6       12
9      8      10       11

Example 1: Remove Rows with Any Zeros Using Base R

The following code shows how to remove rows with any zeros by using the apply() function from base R:

#create new data frame that removes rows with any zeros from original data frame
df_new <- df[apply(df!=0, 1, all),]

#view new data frame
df_new

  points assists rebounds
2      7       2        8
3      8       2        7
5     12       4        6
6     14       3        5
8     10       6       12
9      8      10       11

Notice that the three rows with zero values in them have been removed.

Example 2: Remove Rows with Any Zeros Using dplyr

The following code shows how to remove rows with any zeros by using the filter_if() function from the dplyr package in R:

#create new data frame that removes rows with any zeros from original data frame
df_new <- filter_if(df, is.numeric, all_vars((.) != 0))

#view new data frame
df_new

  points assists rebounds
1      7       2        8
2      8       2        7
3     12       4        6
4     14       3        5
5     10       6       12
6      8      10       11

Notice that the three rows with zero values in them have been removed.

This matches the result that we got using base R.

Note: We used the is.numeric function to specify that all numeric variables in the data frame must be non-zero.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Remove Empty Rows from Data Frame in R
How to Remove Columns with NA Values in R
How to Remove Duplicate Rows in R

Leave a Reply

Your email address will not be published.