title: R count occurrences of an element by groups
body: <p>What is the easiest way to count the occurrences of a an element on a vector or data.frame at every grouop?<br>
  I don't mean just counting the total (as other stackoverflow questions ask) but giving a different number to every succesive occurence.</p>
  
  <p>for example for this simple dataframe: (but I will work with dataframes with more columns)</p>
  
  <pre><code>mydata &lt;- data.frame(A=c("A","A","A","B","B","A", "A"))
  </code></pre>
  
  <p>I've found this solution:</p>
  
  <pre><code>cbind(mydata,myorder=ave(rep(1,nrow(mydata)),mydata$A, FUN=cumsum))   
  </code></pre>
  
  <p>and here the result:</p>
  
  <pre><code> A myorder  
   A       1  
   A       2  
   A       3  
   B       1  
   B       2  
   A       4  
   A       5  
  </code></pre>
  
  <p>Isn't there any single command to do it?. Or using an specialized package?</p>
  
  <p>I want it to later use tidyr's spread() function.</p>
  
  <p>My question is not the same than 
  <a href="https://stackoverflow.com/questions/9809166/is-there-an-aggregate-fun-option-to-count-occurrences">Is there an aggregate FUN option to count occurrences?</a>
  because I don't want to know the total number of occurrencies at the end but the cumulative occurencies till every element.</p>
  
  <p>OK, my problem is a little bit more complex</p>
  
  <pre><code>mydata &lt;- data.frame(group=c("x","x","x","x","y","y", "y"), letter=c("A","A","A","B","B","A", "A"))
  </code></pre>
  
  <p>I only know to solve the first example I wrote above.
  But what happens when I want it also by a second grouping variable?
  something like occurrencies(letter) by group.</p>
  
  <pre><code>group letter  "occurencies within group"  
   x      A       1  
   x      A       2  
   x      A       3  
   x      B       1  
   y      B       1  
   y      A       1  
   y      A       2  
  </code></pre>
  
  <p>I've found the way with   </p>
  
  <blockquote>
    <p>ave(rep(1,nrow(mydata)),list(mydata$group, mydata$letter), FUN=cumsum)<br>
    though it shoould be something easier.</p>
  </blockquote>