Search code examples
rdataframeif-statementdelete-row

Use the categorical values of columns to delete the idex in R


I made a simple data as follow:

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

id stands for specific id number of a person. What I want to do now is delete the whole id if aequals 1. Aso, I want to delete the whole id if b equals 1. In this example, the desired output should be like this:

data<-data.frame(id=c(2,2,2),
                 a=c(0,0,0),
                 b=c(0,0,0))

In my actual data, there are hundreds of id,so I want to know method to do this.


Solution

  • With Base R,

    data[!(data$id %in% unique(data[(data$a == 1) |  (data$b == 1),"id"])),]
    

    gives,

    #       id a b
    #     4  2 0 0
    #     5  2 0 0
    #     6  2 0 0