title: Create a group after a condition in R
body: <p>I am trying to split my data in two based on a gap in the dates. The problem is that in the real data, the duration of the observations is not constant. I am assigning all values of lactation to be 1, and trying to make everything after the long gap to become two.
  What I am trying to do:
  Identify the gap in days, if the gap is longer than 20 days, we will start counting from 1 again using group_by and row_number.
  The problem here is that the lag() function is not carrying the new value after the condition.</p>
  <pre><code>    ###Code
  library(dplyr)
  library(lubridate)
  
  #simulating the data
  
  name&lt;-&quot;cow1&quot;
  milk&lt;-rnorm(500,15,6)
  date1&lt;-seq(ymd('2012-01-01'),ymd('2012-09-06'),by='days') %&gt;%  as_tibble()
  date2&lt;-seq(ymd('2013-01-01'),ymd('2013-09-07'),by='days') %&gt;% as_tibble()
  date&lt;-bind_rows(date1,date2) %&gt;% rename(&quot;day&quot;=value)
  cow1&lt;- milk  %&gt;% as_tibble() %&gt;% rename(&quot;Yield&quot;=value) %&gt;%  mutate(cowid=name,day=date$value)  
  
   cow1.1 &lt;- cow1 %&gt;% mutate(lactation=1) %&gt;%  
     mutate(gap = day - lag(day, default = day[1])) %&gt;% 
     mutate(lactation=ifelse(gap&gt;20,lag(lactation)+1,lag(lactation))) %&gt;%
  group_by(lactation) %&gt;% mutate(dim=row_numer()) 
  </code></pre>
  <p>Sample result:</p>
  <pre><code>Row Yield  cowid    day   lactation gap
  250 3.1429436 cow1 2012-09-06 1 1 days 
  251 10.1427923 cow1 2013-01-01 2 117 days 
  252 19.8654469 cow1 2013-01-02 1 1 days 
  </code></pre>
  <p>Desired result:</p>
  <pre><code>Row Yield  cowid    day   lactation gap
  250 3.1429436 cow1 2012-09-06 1 1 days 
  251 10.1427923 cow1 2013-01-01 2 117 days 
  252 19.8654469 cow1 2013-01-02 2 1 days 
  </code></pre>