title: Identify time gap in large data
body: <p>I'm working on a function to identify a gap in a series of start/end dates. The output should be FALSE if a start date begins later than 1 day after any of the previous end dates.</p>
  
  <p>DATA:</p>
  
  <pre><code>df &lt;- data.frame('ID' = c('1','1','1','1','1','1'), 'start' = as.Date(c('2010-01-01', '2010-01-03', '2010-01-05', '2010-01-09','2010-02-01', '2010-02-10')),
                   'end' = as.Date(c('2010-01-03', '2010-01-22', '2010-01-07', '2010-01-12', '2010-02-10', '2010-02-12')))
  </code></pre>
  
  <p>DESIRED OUTPUT: </p>
  
  <pre><code>  ID      start        end  continuous
  1  1 2010-01-01 2010-01-03 FALSE
  2  1 2010-01-03 2010-01-22 TRUE
  3  1 2010-01-05 2010-01-07 TRUE
  4  1 2010-01-09 2010-01-12 TRUE
  5  1 2010-02-01 2010-02-10 FALSE
  6  1 2010-02-10 2010-02-12 TRUE 
  </code></pre>
  
  <p>This code gets the desired result on this small dataset:</p>
  
  <pre><code>df$continuous &lt;-
    sapply(split(df, df$ID),
                  function(x) {
                    lapply(1:nrow(x),
                           function(y) {
                             any(x$start[y] - x$end[-(y:NROW(x$end))] &lt;= 1)
                           })
                  })
  </code></pre>
  
  <p>However, applying this to a bigger set (>100,000 observations) with many different IDs it still creates wrong output. Example:</p>
  
  <pre><code> ID         start       end            continuous
   2    2015-01-15   2015-01-15             FALSE
   2    2015-01-16   2015-01-17             TRUE
   2    2015-01-16   2015-01-17            FALSE #wrong, should be TRUE
   2    2015-01-17   2015-01-19             TRUE
   2    2015-01-20   2015-01-22             TRUE
   2    2015-01-22   2015-01-23            FALSE #wrong, should be TRUE
   2    2015-01-26   2015-01-26             TRUE
   2    2015-01-26   2015-01-30             TRUE
   2    2015-01-26   2015-01-26            FALSE #wrong, should be TRUE
   2    2015-02-01   2015-02-06             TRUE #wrong, should be FALSE
  </code></pre>
  
  <p>Anyone knows why?</p>