title: How to calculate time difference with previous row of a data.frame by group
body: <p>The problem I am trying to solve is that I have a data frame with a sorted POSIXct variable in it. Each row is categorized and I want to get the time differences between each row for each level and add that data back into a new variable. The reproducible problem is as below.
  The below function is just for creating sample data with random times 
  for the purpose of this question. </p>
  
  <pre><code>random.time &lt;- function(N, start, end) {
    st &lt;- as.POSIXct(start)
    en &lt;- as.POSIXct(end)
    dt &lt;- as.numeric(difftime(en, st, unit="sec"))
    ev &lt;- sort(runif(N, 0, dt))
    rt &lt;- st + ev
    return(rt)
  }
  </code></pre>
  
  <p>The code for simulating the problem is as below:</p>
  
  <pre><code>set.seed(123)
  category &lt;- sample(LETTERS[1:5], 20, replace=TRUE)
  randtime &lt;- random.time(20, '2015/06/01 08:00:00', '2015/06/01 18:00:00')
  df &lt;- data.frame(category, randtime)
  </code></pre>
  
  <p>The expected resulting data frame  is as below:</p>
  
  <pre><code>&gt;category randtime timediff (secs)
  &gt;A  2015-06-01 09:05:00 0
  &gt;A  2015-06-01 09:06:30 90
  &gt;A  2015-06-01 09:10:00 210
  &gt;B  2015-06-01 10:18:58 0
  &gt;B  2015-06-01 10:19:58 60
  &gt;C  2015-06-01 08:14:00 0
  &gt;C  2015-06-01 08:16:30 150
  </code></pre>
  
  <p>Each subgroup in the output will have the first row with timediff value of 0 as there is no previous row. I was able to group by category and call the following function to calculate the differences but could not get it to collate the final output for all category groups.</p>
  
  <pre><code>getTimeDiff &lt;- function(x) {
    no_rows &lt;- nrow(x)
    if(no_rows &gt; 1) {
      for(i in 2:no_rows) {
        t &lt;- x[i, "randtime"] - x[i-1, "randtime"]
      }
    }
  }
  </code></pre>
  
  <p>I have been at this for two days now without luck so would greatly appreciate any help. 
  Thanks.</p>