title: Calculating elapsed time in R given one column
body: <p>I currently have data that has one column of dates and times (in POSIXct format already) and a column showing the "ON/OFF" state of a data logger.  I need to calculate the time elapsed between the OFF (0) and ON (1) states to calculate delay.  </p>
  
  <p>Data looks like this:</p>
  
  <pre><code>onoff            datetime
  1     1 2014-05-14 16:26:57
  2     0 2014-05-14 16:27:02
  3     1 2014-05-14 16:27:06
  4     0 2014-05-14 16:27:12
  5     1 2014-05-14 16:28:10
  6     0 2014-05-14 16:28:15
  </code></pre>
  
  <p>I am struggling with how to do this calculation.  In Excel, I created an if-then statement to subtract each row from the previous row given a "0" condition for the ON/OFF variable.  </p>
  
  <p>I think the best way to do this in R may be to create 2 new columns, each corresponding to the subset when onoff =1 or 0.  How can I do this?  If I can create two columns, it will be much easier to calculate using the timediff function (and can rule out NA or very large values).  Thanks for your help, I am very new at this but haven't found an answer to my specific problem via Google or other help sites.  </p>