title: Calculate differences between rows faster than a for loop?
body: <p>I have a data set that looks like this:</p>
  
  <pre><code>ID   |   DATE    | SCORE
  -------------------------
  123  |  1/15/10  |  10
  123  |  1/1/10   |  15
  124  |  3/5/10   |  20
  124  |  1/5/10   |  30
  ...
  </code></pre>
  
  <p>So to load the above snippet as a data frame, the code is:</p>
  
  <pre><code>id&lt;-c(123,123,124,124)
  date&lt;-as.Date(c('2010-01-15','2010-01-01','2010-03-05','2010-01-05'))
  score&lt;-c(10,15,20,30)
  data&lt;-data.frame(id,date,score)
  </code></pre>
  
  <p><br>
  I'm trying to add a column that calculates the "days since last record for this ID".</p>
  
  <p>Right now I'm using a FOR loop that looks something like this:</p>
  
  <pre><code>data$dayssincelast &lt;- rep(NA, nrow(data))
  for(i in 2:nrow(data)) {
    if(data$id[i] == data$id[i-1]) 
      data$dayssincelast[i] &lt;- data$date[i] - data$date[i-1]
  }
  </code></pre>
  
  <p><br></p>
  
  <p><strong>Is there a faster way to do this?</strong> (I've looked a bit into APPLY but can't quite figure out a solution besides a FOR loop.)</p>
  
  <p>Thanks in advance!</p>