How to delete rows where all the columns are zero

后端 未结 4 1712
旧时难觅i
旧时难觅i 2020-12-07 03:32

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 
         


        
4条回答
  •  孤街浪徒
    2020-12-07 03:45

    Why use sum? it is much more efficient to simply check if all elements are zero. I would do

    dat = dat[!apply(dat, 1, function(x) all(x == 0)), ]
    

    If you need to keep track of which rows were removed:

    indremoved = which(apply(dat, 1, function(x) all(x == 0)) )
    dat = dat[ -indremoved, ]
    

提交回复
热议问题