Skip to Content

How to conditionally delete rows from data frame

I have the following data frame

id<-c(1,1,1,1,2,2,2,2,3,3,3,3)
time<-c(0,1,2,3,0,1,2,3,0,1,2,3)
value<-c(1,1,6,1,2,6,2,2,1,1,6,1)
 
d<-data.frame(id, time, value)

The value 6 appears only once for each id. For every id, i would like to remove all rows with time greater than the time of the value 6

I would like the final data frame to have all observations for all ID's without "6". For those IDs having a "6" observation, i would like all observations with time < of that the time of the 6 observation.

I've searched SO, there are several questions (and answers) about conditional row deletion, but i found nothing close to what I need.

In the above case the final data frame should be

  id time value
1   1    0     1
2   1    1     1
3   1    2     6
5   2    0     2
6   2    1     6
9   3    0     1
10  3    1     1
11  3    2     6

Thank you very much.