Question: Hi I have a data frame like below:

```
 id=rep(c(1:3),each=3)
 status=rep(c(1,0,1),each=3)
 event=c(0,1,1,0,0,0,1,1,1)
 cbind(id,status,event)
       id status event
  [1,]  1      1     0
  [2,]  1      1     1
  [3,]  1      1     1
  [4,]  2      0     0
  [5,]  2      0     0
  [6,]  2      0     0
  [7,]  3      1     1
  [8,]  3      1     1
  [9,]  3      1     1

```

I want to keep or indicate the rows that is before 'event'==1 and the first row of 'event'==1 as below: 

```
id status event ind
1    1     0     T
1    1     1     T
1    1     1     F
2    0     0     T
2    0     0     T
2    0     0     T
3    1     1     T
3    1     1     F
3    1     1     F

```

or 

```
id status event 
1    1     0    
1    1     1    
2    0     0    
2    0     0    
2    0     0    
3    1     1    

```

Anybody has good ideas?
Thanks a lot!!

Answer: 
If `DF` is the input data frame then:

```
DF$ind <- ave(DF$event == 1, DF$id, FUN = function(x) !cumsum(c(0, head(x, -1))))

```

In the case of the example it gives:

```
> DF
  id status event   ind
1  1      1     0  TRUE
2  1      1     1  TRUE
3  1      1     1 FALSE
4  2      0     0  TRUE
5  2      0     0  TRUE
6  2      0     0  TRUE
7  3      1     1  TRUE
8  3      1     1 FALSE
9  3      1     1 FALSE

```
This approach uses plyr to split up the data.frame by `id`. Then the cases of `event==0` and `event==1` are handled separately, and then later combined. A check is included in case there aren't any `event==1` rows for a given `id` value.

```
require(plyr)

SelectRecords <- function( d ) {
  eventIsZero <- which(d$event==0)
  eventIsOne <- which(d$event==1)

  if( length(eventIsOne) >= 1 )
    selectedIndices <- c(eventIsZero, min(eventIsOne, na.rm=T))
  else    
    selectedIndices <- eventIsZero

  return( d[selectedIndices, ] )
}

ddply(ds, .variables="id", .fun=SelectRecords)

```