title: R How to subtract date from next date below and group by?
body: <p>I have the following data (this is a sample, my dataset is quite large):</p>
  
  <pre><code>ID| Date        
  A | 2010-12-30 
  A | 2010-12-13 
  A | 2010-08-23 
  B | 2011-06-24 
  B | 2011-06-13 
  B | 2010-02-20 
  </code></pre>
  
  <p>What I need to do is to calculate the difference between dates, based on the ID. The calculation must start from the first row and subtract the date on the row below. </p>
  
  <p>So for the above data, the desired output would be the DateDiff column below:</p>
  
  <pre><code>ID| Date        | DateDiff
  A | 2010-12-30  | 17       (which is 2010-12-30 - 2010-12-13) 
  A | 2010-12-13  | 112      (which is 2010-12-13 - 2010-08-23) 
  A | 2010-08-23  | 0        (this result should be 0 as the ID (A) does not match the ID below (B)   
  B | 2011-06-24  | 11       (which is 2011-06-24 - 2011-06-13)
  B | 2011-06-13  | 478      (which is 2011-06-13 - 2010-02-20)
  B | 2010-02-20  | 0        (this result is 0 again as there is no ID in the next row thus the ID (B) does not match the ID below)
  </code></pre>
  
  <p>I have used the following code which is close to the desired result:</p>
  
  <pre><code>df$DateDiff &lt;- ave(as.numeric(df$DATE), df$ID, FUN=function(x) c(0,abs(diff(x))))
  </code></pre>
  
  <p>However, it calculates by subtracting the second date from the first, and therefore entering in 0 in the first row, like so:</p>
  
  <pre><code>ID| Date        | DateDiff
  A | 2010-12-30  | 0 (as there is no date above)       
  A | 2010-12-13  | 17
  A | 2010-08-23  | 112 (as it calculates the diff between the first date in ID (B) from the last in ID (A)  
  B | 2011-06-24  | 0
  B | 2011-06-13  | 11 
  B | 2010-02-20  | 478        
  </code></pre>
  
  <p>As you can see, the result is close but not quite there. I have searched long and hard but have not been able to locate a solution.</p>