title: Create Unique Groups Based On Consecutive Observations
body: <p>I am looking for a data.table solution for the following problem.</p>
  <p>Suppose that I have the following data.table:</p>
  <pre><code>library(data.table)
  library(lubridate)
  
  DT &lt;- data.table(year = c(2016, 2017, 2018, 2019, 2020),
                   store = c(1,2,2,2,1),
                   name = c(&quot;J&quot;, &quot;J&quot;, &quot;J&quot;, &quot;J&quot;, &quot;J&quot;),
                   begin = c(&quot;2016-01-01&quot;, &quot;2017-10-22&quot;, &quot;2018-01-01&quot;, &quot;2019-01-01&quot;, &quot;2020-01-26&quot;),
                   end = c(&quot;2017-02-19&quot;, &quot;2017-12-31&quot;, &quot;2018-12-31&quot;, &quot;2020-01-26&quot;, &quot;2020-12-31&quot;))
                   
  
  DT[, `:=`(begin = ymd(begin),
            end = ymd(end))]
  
  </code></pre>
  <p>I would like to summarize the data.table such that I have the beginning and end dates for each person (indicated by the variable name) at each store. So I would like a data.table that looks like:</p>
  <pre><code> store   name      begin        end
     &lt;num&gt; &lt;char&gt;     &lt;Date&gt;     &lt;Date&gt;
  1:     1      J 2016-01-01 2017-02-19
  2:     1      J 2020-01-26 2020-12-31
  3:     2      J 2017-10-22 2020-01-26
  
  </code></pre>
  <p>The issue with the following command:</p>
  <pre><code>DT_sum &lt;- DT[, .(begin = min(begin),
                   end = max(end)), by =.(store, name)]
  
  
  </code></pre>
  <p>is that it does not account for the fact that &quot;J&quot; leaves the store, and returns later. Thus, the interval is too large. I am wondering if there was a concise data.table way of handling this problem, where a person can return to a single store multiple times throughout their tenure.</p>
  <p>Thanks!</p>