title: difftime between rows using dplyr
body: <p>I'm trying to calculate the time difference between two timestamps in two adjacent rows using the dplyr package. Here's the code:</p>
  
  <pre><code>    tidy_ex &lt;- function () {
  
      library(dplyr)
  
      #construct example data
      data &lt;- data.frame(code = c(10888, 10888, 10888, 10888, 10888, 10888, 
                                      10889, 10889, 10889, 10889, 10889, 10889,
                                      10890, 10890, 10890),
                             station = c("F1", "F3", "F4", "F5", "L5", "L7", "F1",
                                         "F3", "F4", "L5", "L6", "L7", "F1", "F3", "F5"),
                             timestamp = c(1365895151, 1365969188, 1366105495,
                                             1367433149, 1368005216, 1368011698,
                                             1366244224, 1366414926, 1367513240,
                                             1367790556, 1367946420, 1367923973,
                                             1365896546, 1365907968, 1366144207))
  
      # reformat timestamp as POSIXct
      data$timestamp &lt;- as.POSIXct(data$timestamp,origin = "1970-01-01")
  
      #create tbl_df
      data2 &lt;- tbl_df(data)
  
      #group by code and calculate time differences between two rows in timestamp column 
      data2 &lt;- data2 %&gt;%
              group_by(code) %&gt;%
              mutate(diff = c(difftime(tail(timestamp, -1), head(timestamp, -1))))
  
      data2
  
      }
  </code></pre>
  
  <p>The code produces an error message:</p>
  
  <pre><code> Error: incompatible size (5), expecting 6 (the group size) or 1
  </code></pre>
  
  <p>I guess that's because the difference for the last row produces an NA (since there is no further adjacent row). The difftime/head-tails method however works with the plyr package instead of dplyr <a href="https://stackoverflow.com/questions/17015425/difftime-between-2-columns-and-next-row-within-a-variable">(see this StackOverflow post)</a></p>
  
  <p>How can I get it to work using dplyr?</p>