How to remove rows with any zero value

前端 未结 8 652
时光取名叫无心
时光取名叫无心 2020-11-28 07:04

I have a problem to solve how to remove rows with a Zero value in R. In others hand, I can use na.omit() to delete all the NA values or use complete.cases

8条回答
  •  -上瘾入骨i
    2020-11-28 07:32

    I would probably go with Joran's suggestion of replacing 0's with NAs and then using the built in functions you mentioned. If you can't/don't want to do that, one approach is to use any() to find rows that contain 0's and subset those out:

    set.seed(42)
    #Fake data
    x <- data.frame(a = sample(0:2, 5, TRUE), b = sample(0:2, 5, TRUE))
    > x
      a b
    1 2 1
    2 2 2
    3 0 0
    4 2 1
    5 1 2
    #Subset out any rows with a 0 in them
    #Note the negation with ! around the apply function
    x[!(apply(x, 1, function(y) any(y == 0))),]
      a b
    1 2 1
    2 2 2
    4 2 1
    5 1 2
    

    To implement Joran's method, something like this should get you started:

    x[x==0] <- NA
    

提交回复
热议问题