title: Counting Occurrences of a Specific Value Preceding Current Value in R Data Frame Column
body: <p>So I have a data frame:</p>
  <pre><code>index &lt;- c(8,7,6,5,4,3,2,1)
  names &lt;- c(&quot;Joe&quot;, &quot;John&quot;, &quot;Chris&quot;, &quot;Joe&quot;, &quot;Al&quot;, &quot;Fred&quot;, &quot;Joe&quot;, &quot;John&quot;)
  values &lt;- c(1,9,2,9,1,3,3,7)
  df &lt;- data.frame(index,names,values)
  </code></pre>
  <p>I'd like to add a fourth column &quot;running.count&quot; and &quot;running.total&quot;</p>
  <p>I'd like &quot;running.count&quot; to populate with the number of instances of a given name in the data frame <em>with an id higher than the row being filled</em>. So running.count[7] should be 2 since it's the third instance of Joe (two instance of &quot;Joe&quot; above this row)</p>
  <p>Similarly I'd like &quot;running.total&quot; to include the sum of the relevant numbers from values (i.e. running.totals[7] should be a sum of &quot;values&quot; for the relevant rows. I.e. running.count[7] should be 10 since we have 1 and 9 with the first two instances of Joe.</p>
  <p>I'm coming from an excel background, and conceptually I just want to &quot;COUNTIF&quot; and &quot;SUMIF&quot; a range from the highest index to index n-1, but I'm struggling to find an elegant way to do this in R.</p>
  <p>So far I've come up with essentially creating a new data frame each time that simply has all the rows with a higher ID than the row I'm looking to fill, but this is a pretty inelegant solution for how much data I'm trying to perform this calculation for.</p>
  <p>Any help would be greatly appreciated. Thank you!</p>