title: Time elapsed with condition in data.table
body: <p>My objective is to take the difference in minutes between first and last timestamp by <code>id</code> where timestamps are spaced 10 minutes apart.  Standalone timestamps should be assigned <code>10</code>.  If there is a sequence of timestamps, then the difference in time should equal the last in the sequence - first in the sequence.  For example: </p>
  
  <pre><code>&gt; test
     id           timestamp
  1   1 2018-01-02 00:40:00
  2   1 2018-01-02 00:50:00
  4   1 2018-01-02 01:10:00
  5   1 2018-01-02 01:20:00
  6   1 2018-01-02 01:30:00
  7   1 2018-01-02 02:00:00
  8   2 2018-01-02 01:50:00
  9   2 2018-01-02 02:00:00
  10  2 2018-01-02 02:10:00
  11  2 2018-01-02 02:20:00
  12  2 2018-01-02 02:30:00
  13  2 2018-01-02 02:40:00
  14  2 2018-01-02 03:10:00
  15  2 2018-01-02 03:20:00
  </code></pre>
  
  <p>Should produce an output of: </p>
  
  <pre><code>&gt; output
    id                                    period elapsed
  1  1 2018-01-02 00:40:00 - 2018-01-02 00:50:00      10
  2  1 2018-01-02 01:10:00 - 2018-01-02 01:30:00      20
  3  1                       2018-01-02 02:00:00      10
  4  2 2018-01-02 01:50:00 - 2018-01-02 02:40:00      50
  5  2 2018-01-02 03:10:00 - 2018-01-02 03:20:00      10
  </code></pre>
  
  <p>Any suggestions with <code>data.table</code> or <code>dplyr</code> would be appreciated.  I'm guessing the pseudocode would look something like this </p>
  
  <pre><code> setDT(teset)
      test[, .(elapsed := ifelse(difftime(last_timestamp, first_timestamp) &gt; 10, difftime(last_timestamp, first_timestamp), 10) .(period := paste(first_timestamp, "-", last_timestamp)), by = id]
  </code></pre>
  
  <p>Here is the sample dataset:</p>
  
  <pre><code>   &gt; dput(test)
  structure(list(id = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 
  2), timestamp = structure(c(1514875200, 1514875800, 1514877000, 
  1514877600, 1514878200, 1514880000, 1514879400, 1514880000, 1514880600, 
  1514881200, 1514881800, 1514882400, 1514884200, 1514884800), class = c("POSIXct", 
  "POSIXt"), tzone = "America/Chicago")), .Names = c("id", "timestamp"
  ), row.names = c(1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
  13L, 14L, 15L), class = "data.frame")
  </code></pre>