Search code examples
rdata-cleaning

Using R to filter special rows


I have a question which has bothered me for a long time.I have a data frame as below...

ll <- data.frame(id=1:10,
                 A=c(rep(0,5),3,4,5,0,2),
                 B=c(1,4,2,0,3,0,3,24,0,0),
                 C=c(0,3,4,5,0,4,0,6,0,5),
                 D=c(0,1,2,0,42,4,0,3,8,0))

> ll
   id A  B C  D
1   1 0  1 0  0
2   2 0  4 3  1
3   3 0  2 4  2
4   4 0  0 5  0
5   5 0  3 0 42
6   6 3  0 4  4
7   7 4  3 0  0
8   8 5 24 6  3
9   9 0  0 0  8
10 10 2  0 5  0

I want to filter out some special rows which have more than one "0" such as...

    id A  B C  D
1   1  0  1 0  0

I want the final output as...

   id A  B C  D
2   2 0  4 3  1
3   3 0  2 4  2
6   6 3  0 4  4
8   8 5 24 6  3

Solution

  • You can just use rowSums:

    > ll[rowSums(ll == 0) <= 1, ]
      id A  B C D
    2  2 0  4 3 1
    3  3 0  2 4 2
    6  6 3  0 4 4
    8  8 5 24 6 3
    

    If there are any columns that shouldn't be included, you can drop them in the rowSums step. For example, I assume "id" would not be included. If that's the case, then you can do:

    ll[rowSums(ll[-1] == 0) <= 1, ]