Calculate cumulative percentage for each unit over a time series
<p>I have the following data:</p>

<pre><code>ID &lt;- c(1, 2, 1, 2, 1, 2)
year  &lt;- c(1, 1, 2, 2, 3, 3)
population.served  &lt;- c(100, 200, 300, 400, 400, 500)
population  &lt;- c(1000, 1200, 1000, 1200, 1000, 1200)
all &lt;- data.frame(ID, year, population.served, population)
</code></pre>

<p>I want to calculate the % of the population served for each ID by year. I've attempted this, but I only manage to calculate the % served for each year. I need some way for iterating through each ID and year, to capture the cumulative sum as the numerator. </p>

<p>I want the data to look like this:</p>

<pre><code>ID &lt;- c(1, 2, 1, 2, 1, 2)
year  &lt;- c(1, 1, 2, 2, 3, 3)
population.served  &lt;- c(100, 200, 300, 400, 400, 500)
population  &lt;- c(1000, 1200, 1000, 1200, 1000, 1200)
cumulative.served &lt;- c(10, 16.7, 40, 50, 80, 91.7)
all &lt;- data.frame(ID, year, population.served, population, cumulative.served)
</code></pre>