title: Add an index (or counter) to a dataframe by group in R
body: <p>I have a df like</p>
  
  <pre><code>ProjectID Dist
    1        x
    1        y
    2        z
    2        x
    2        h
    3        k
    ....     ....
  </code></pre>
  
  <p>I want to add a third column such that we have an incrementing counter for each ProjectID:</p>
  
  <pre><code>ProjectID Dist counter
    1        x     1
    1        y     2
    2        z     1
    2        x     2
    2        h     3
    1        k     3
    ....     ....
  </code></pre>
  
  <p>I've had a look at <code>seq</code> <code>rank</code> and a couple of other bits particularly looking to see if I could use <code>ddply</code> to help:</p>
  
  <pre><code>df$counter &lt;- ddply(df,.(projectID), function(x).....? )
  </code></pre>
  
  <p>I think I could adapt this answer <a href="https://stackoverflow.com/questions/8604568/how-to-create-a-counter-numeration-by-group-in-r">How to create a counter/numeration by group?</a> but would prefer something using something like ddply (I can't find an equivalent of cumsum but I think that's the same principle here: <a href="https://stackoverflow.com/questions/21005925/create-ascending-series-of-integers-by-group-in-pandas">Create ascending series of integers by group in Pandas</a> ).  That'd let me index occurrences in a list (and e.g. merge on this).</p>