How to delete rows where all the columns are zero

Viewed 8278

I have the following data frame

dat <- data.frame(a = c(0,0,2,3), b= c(1,0,0,0), c=c(0,0,1,3))

Which prints:

> dat 
  a b c
1 0 1 0
2 0 0 0
3 2 0 1
4 3 0 3

I want to remove rows where all the columns are zeros, resulting in this:

  a b c
1 0 1 0 
3 2 0 1
4 3 0 3

How can I achieve that?

I tried this but failed:

> row_sub = apply(dat, 1, function(row) all(row !=0 ))
> dat[row_sub,]
[1] a b c
<0 rows> (or 0-length row.names)
6 Answers

dat[as.logical(rowSums(abs(dat))), ] or if you wanna handle NA's in your zeros row as well dat[as.logical(rowSums(abs(dat), na.rm = TRUE)), ]

We can use

dat[t(sapply( data.frame(t(dat)) , \(x) any(x != 0))) , ]
  • output
  a b c
1 0 1 0
3 2 0 1
4 3 0 3
Related