title: converting timestamp state event logs to runtime in R data.table
body: <p>I have large data set of logged timestamps corresponding to state changes (e.g., light switch flips) that look like this:</p>
  
  <pre><code>library(data.table)
  library(lubridate)
  foo &lt;- 
    data.table(ts = ymd_hms("2013-01-01 01:00:01",
                            "2013-01-01 05:34:34",
                            "2013-01-02 14:12:12",
                            "2013-01-02 20:01:00",
                            "2013-01-02 23:01:00",
                            "2013-01-03 03:00:00",
                            "2013-05-04 05:00:00"),
               state = c(1, 0, 1, 0, 0, 1, 0) )
  </code></pre>
  
  <p>And I'm trying to (1) convert the history of state logs into run-times in seconds, and (2) convert these into daily cumulative run-times. Most (but not all) of the time, consecutive logged state values alternate. This is a kludgy start, but it falls a little short. </p>
  
  <pre><code>foo[, dif:=diff(ts)]
  foo[state==1][, list(runtime = sum(dif)), .(floor_date(ts, "day"))]
  </code></pre>
  
  <p>In particular, when the state is "on" during a period that crosses midnight, this approach isn't smart enough to split things up, and incorrectly reports runtime longer than one day. Also, using <code>diff</code> is not so intelligent either, since it will make mistakes if there are consecutive identical states or <code>NAs</code>. </p>
  
  <p>Any suggestions that will correctly resolve runtime that are still fast and efficient for large data sets?</p>