title: Calculate time using the last two dates with a condition in R
body: <p>I need to calculate a time difference by a record_id using two consecutive dates but only if the category has a specific value that is repeated (category == &quot;1&quot;).</p>
  <p>My data frame is</p>
  <pre><code>structure(list(record_id = c(&quot;P1&quot;, &quot;P1&quot;, &quot;P1&quot;, &quot;P2&quot;, &quot;P2&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P4&quot;, &quot;P4&quot;, &quot;P4&quot;, &quot;P5&quot;, &quot;P5&quot;, &quot;P5&quot;, &quot;P5&quot;), visit_date = structure(c(1547596800, 1548806400, 1552608000, 1560988800, 1611187200, 1576195200, 1577664000, 1579132800, 1594857600, 1609459200, 1577836800,1580515200, 1612137600, 1548979200, 1583020800, 1585699200, 1617235200), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;UTC&quot;), 
  category = c(0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 
  1, 1)), row.names = c(NA, -17L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;))
  </code></pre>
  <p>I need to create a variable (time) as a date difference between visit_dates by record IDs ONLY if they have two consecutive category==1.</p>
  <p>Like this:</p>
  <pre><code>structure(list(record_id = c(&quot;P1&quot;, &quot;P1&quot;, &quot;P1&quot;, &quot;P2&quot;, &quot;P2&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P3&quot;, &quot;P4&quot;, &quot;P4&quot;, &quot;P4&quot;), visit_date = structure(c(1547596800, 1548806400, 1552608000, 1560988800, 1611187200, 1576195200, 1577664000, 1579132800, 1594857600, 1609459200, 1577836800, 1580515200, 1612137600), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;UTC&quot;), category = c(0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1), time = c(NA, NA, NA, NA, NA, 169, 169, 169, 169, 169, 366, 366, 366)), row.names = c(NA, -13L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;))
  </code></pre>
  <p>Note that P5 the date difference is with the first category 1 and the last category 1</p>