title: Transform rows of sequential dates into column of date range
body: <p>I must turn observations that meet a condition, a binary flag, on certain dates into a table of observations with the date range that they meet the flag.</p>
  
  <p>Sample data look like this: </p>
  
  <pre><code>id &lt;- c(1001, 1001, 1001, 1002, 1002, 1002, 1003, 1003, 1003)
  date &lt;- c("2016-06-20", "2016-06-21", "2016-06-22", "2016-06-20", 
            "2016-06-21", "2016-06-22", "2016-06-20", "2016-06-21", 
            "2016-06-22")
  flag &lt;- c(1, 0, 0, 1, 1, 0, 1, 0, 1)
  mydata &lt;- data.frame(id, date, flag)
  
    id       date flag
  1001 2016-06-20    1
  1001 2016-06-21    0
  1001 2016-06-22    0
  1002 2016-06-20    1
  1002 2016-06-21    1
  1002 2016-06-22    0
  1003 2016-06-20    1
  1003 2016-06-21    0
  1003 2016-06-22    1
  </code></pre>
  
  <p>I am thinking of this as a two step process. </p>
  
  <p><strong>Step 1: determine whether the flag occurs on consecutive days.</strong></p>
  
  <p>This is similar to this question - <a href="https://stackoverflow.com/questions/37342412/r-find-dates-consecutive">R, find, dates, consecutive</a> - but with a condition, if <code>flag &gt; 0</code>. I try to apply the solution, although it doesn't quite work the same way.</p>
  
  <pre><code>mydata$flag_consecutive &lt;- mydata$flag &gt; 0 &amp; c(NA, diff(as.Date(mydata$date)) == 1)
  
  
    id       date flag flag_consecutive
  1001 2016-06-20    1               NA
  1001 2016-06-21    0            FALSE
  1001 2016-06-22    0            FALSE
  1002 2016-06-20    1            FALSE
  1002 2016-06-21    1             TRUE
  1002 2016-06-22    0            FALSE
  1003 2016-06-20    1            FALSE
  1003 2016-06-21    0            FALSE
  1003 2016-06-22    1             TRUE
  </code></pre>
  
  <p><strong>Step 2: create date range columns</strong></p>
  
  <p>I'm not sure how to approach this part with vectorization in R. 
  If the flag occurs on one day only, the start and end date are the same.
  If the flag occurs on consecutive days, I want to put the first day in the sequence as <code>date_start</code> and the last day as <code>date_end</code>. If there is no flag occurring, drop that from the dataset.</p>
  
  <p>What I'd like to generate is the data formatted this way:</p>
  
  <pre><code>  id flag  date_start     date_end
  1001    1  2016-06-20   2016-06-20
  1002    1  2016-06-20   2016-06-21
  1003    1  2016-06-20   2016-06-20
  1003    1  2016-06-22   2016-06-22
  </code></pre>
  
  <p>If you can provide any guidance on step 1 or step 2, I am very thankful. I am thinking in circles and am not sure whether step 1 is even needed.</p>