Subtract value in previous row for each section of a data frame that corresponds to a certain ID in R
<p>Say I have a data frame with three columns:</p>

<pre><code>df&lt;-data.frame(ID=c(101,101,101,102,102,102,102,104,104), 
Year=c(2005,2006,2007,1998,1999,2000,2001,2012,2013),
AnnualSpending=c(94.50,87.63,44.95,65.37,44.22,25.64,125.78,250.87,100))

   ID Year AnnualSpending
1 101 2005          94.50
2 101 2006          87.63
3 101 2007          44.95
4 102 1998          65.37
5 102 1999          44.22
6 102 2000          25.64
7 102 2001         125.78
8 104 2012         250.87
9 104 2013         100.00
</code></pre>

<p>How can I subtract the previous value of AnnualSpending and add the result to a new column so that the first row corresponding to each ID is always 0?</p>

<pre><code>changeFromPrevious
0
-6.87
-42.68
0
-21.15
-18.58
100.14
0
-150.87
</code></pre>