title: How to flatten / merge overlapping time periods
body: <p>I have a large data set of time periods, defined by a 'start' and and an 'end' column. Some of the periods overlap.</p>
  
  <p>I would like to combine (flatten / merge / collapse) all overlapping time periods to have one 'start' value and one 'end' value.</p>
  
  <p>Some example data:</p>
  
  <pre><code>  ID      start        end
  1  A 2013-01-01 2013-01-05
  2  A 2013-01-01 2013-01-05
  3  A 2013-01-02 2013-01-03
  4  A 2013-01-04 2013-01-06
  5  A 2013-01-07 2013-01-09
  6  A 2013-01-08 2013-01-11
  7  A 2013-01-12 2013-01-15
  </code></pre>
  
  <p>Desired result:    </p>
  
  <pre><code>  ID      start        end
  1  A 2013-01-01 2013-01-06
  2  A 2013-01-07 2013-01-11
  3  A 2013-01-12 2013-01-15
  </code></pre>
  
  <p>What I have tried:</p>
  
  <pre><code>  require(dplyr)
    data &lt;- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), class = "factor", .Label = "A"), 
      start = structure(c(1356998400, 1356998400, 1357084800, 1357257600, 
      1357516800, 1357603200, 1357948800), tzone = "UTC", class = c("POSIXct", 
      "POSIXt")), end = structure(c(1357344000, 1357344000, 1357171200, 
      1357430400, 1357689600, 1357862400, 1358208000), tzone = "UTC", class = c("POSIXct", 
      "POSIXt"))), .Names = c("ID", "start", "end"), row.names = c(NA, 
  -7L), class = "data.frame")
  
  remove.overlaps &lt;- function(data){
  data2 &lt;- data
  for ( i in 1:length(unique(data$start))) {
  x3 &lt;- filter(data2, start&gt;=data$start[i] &amp; start&lt;=data$end[i])
  x4 &lt;- x3[1,]
  x4$end &lt;- max(x3$end)
  data2 &lt;- filter(data2, start&lt;data$start[i] | start&gt;data$end[i])
  data2 &lt;- rbind(data2,x4)  
  }
  data2 &lt;- na.omit(data2)}
  
  data &lt;- remove.overlaps(data)
  </code></pre>