title: Select all rows up to and including first occurrence by group in a data frame
body: <p>I ve been scratching my head a little about how to do. I'm reorganising some unbalanced panel data (stacked/long format). I need to keep all the rows up to and including the first occurrence of variable (indc=D) value by group (id) and also keep the rows for groups where this has not occurred yet. The only rows I wish to discard are rows per group where there is a second or more value of the indicator variable (indc=D). I also need to keep all the columns in the dataframe.</p>
  
  <pre><code># Data 
  id&lt;-factor(c(1,1,1,2,2,2,2,2, 3,3,3,3,3,3,4,4))
  time&lt;-c(1,2,3,1,2,3,4,5, 1,2,3,4,5,6, 1,2)
  indc&lt;-factor(c("C","C","D","C","C","C","D","D","C","C","C","C","D","D","C","C"))
  var1&lt;-sample(seq(1,8.5, by=0.5))
  var2&lt;-c(rep(1,8),rep(0,8))
  
  df&lt;-data.frame(id,time,indc,var1,var2)
  </code></pre>
  
  <p>My attempt is using by and match - problem is it returns the last variable as a match and the indices for each group. I m stuck on how to get to the final solution. </p>
  
  <pre><code>attempt&lt;-by(df, df$id, function(x) {match(unique(x$indc=="D"), x$indc=="D")} )
  
  results&lt;-(do.call("rbind", attempt))
  </code></pre>
  
  <p>The desired result is df2 <code>df2&lt;-df[c(1:3,4:7,9:13,15:16),]</code></p>
  
  <p>I'd be very grateful if anyone has ideas on a solution.</p>