title: identify first row in a sequence change in order to find the lag value in another variable in r
body: <p>I have a data frame with an id, a category and a value. The category has runs of sequence of either 'on' or 'off'. I want to identify the first row where the sequence changes to &quot;on&quot; each time this occurs. From this I want to identify the 'value' in the lag and lead rows to this. This needs to be done per group (id)</p>
  <p>I can achieve finding the start of the sequence change by filtering to when the category changes but want to keep the data frame complete in order to find lag and lead values in the value variable.</p>
  <p>Here is a sample data frame.
  So for example in id &quot;b&quot;, I would need to identify the values 54 and 90
  Appreciate any help.</p>
  <pre><code>id &lt;- c(&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;,&quot;c&quot;, &quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot; )
  category &lt;- c(&quot;OFF&quot;, &quot;OFF&quot;, &quot;ON&quot;, &quot;ON&quot;, &quot;ON&quot;, &quot;OFF&quot;, &quot;OFF&quot;, &quot;OFF&quot;, &quot;ON&quot;, &quot;ON&quot;, &quot;OFF&quot;, &quot;OFF&quot;,&quot;OFF&quot;,&quot;OFF&quot;,&quot;OFF&quot;, &quot;ON&quot;, &quot;ON&quot;,&quot;ON&quot;)
  value&lt;- c(100,90,65,55,32,23,45,54,27,90,100,100,100,30,30,25, 45, 67)
  dat&lt;-data.frame(id, category, value)
  dat
  
  
  </code></pre>