Home > Mobile >  event filtering in R
event filtering in R

Time:11-10

Here I have a data as follows:

data<-data.frame(id=c(1,1,1,2,2,2,3,3,3),
                 event=c(1,0,1,0,0,1,0,0,0))

I want to remake data by the following rules. id means a personal number. For each id if id has at least one event, then only filer the rows with events. However, if 'id' ahs no event, then do not filter the rows.

In this case,id=1 and 2 has events but, id=3 has no events. So the expected output of data should be like this:

data<-data.frame(id=c(1,1,2,3,3,3),
                 event=c(1,1,1,0,0,0))

CodePudding user response:

The filtering criteria is event == 1 OR the maximum value of event for that id is 0. So:

library(dplyr)
data %>%
        group_by(id) %>%
        filter(event==1 | max(event)==0)
  • Related