title: Numbering rows within groups in a data frame
body: <p>Working with a data frame similar to this:</p>
  <pre class="lang-r prettyprint-override"><code>set.seed(100)  
  df &lt;- data.frame(cat = c(rep(&quot;aaa&quot;, 5), rep(&quot;bbb&quot;, 5), rep(&quot;ccc&quot;, 5)), val = runif(15))             
  df &lt;- df[order(df$cat, df$val), ]  
  df  
  </code></pre>
  <pre class="lang-none prettyprint-override"><code>   cat        val  
  1  aaa 0.05638315  
  2  aaa 0.25767250  
  3  aaa 0.30776611  
  4  aaa 0.46854928  
  5  aaa 0.55232243  
  6  bbb 0.17026205  
  7  bbb 0.37032054  
  8  bbb 0.48377074  
  9  bbb 0.54655860  
  10 bbb 0.81240262  
  11 ccc 0.28035384  
  12 ccc 0.39848790  
  13 ccc 0.62499648  
  14 ccc 0.76255108  
  15 ccc 0.88216552 
  </code></pre>
  <p>I am trying to add a column with numbering within each group. Doing it this way obviously isn't using the powers of R:</p>
  <pre class="lang-r prettyprint-override"><code> df$num &lt;- 1  
   for (i in 2:(length(df[,1]))) {  
     if (df[i,&quot;cat&quot;]==df[(i-1),&quot;cat&quot;]) {  
       df[i,&quot;num&quot;]&lt;-df[i-1,&quot;num&quot;]+1  
       }  
   }  
   df  
  </code></pre>
  <pre class="lang-none prettyprint-override"><code>   cat        val num  
  1  aaa 0.05638315   1  
  2  aaa 0.25767250   2  
  3  aaa 0.30776611   3  
  4  aaa 0.46854928   4  
  5  aaa 0.55232243   5  
  6  bbb 0.17026205   1  
  7  bbb 0.37032054   2  
  8  bbb 0.48377074   3  
  9  bbb 0.54655860   4  
  10 bbb 0.81240262   5  
  11 ccc 0.28035384   1  
  12 ccc 0.39848790   2  
  13 ccc 0.62499648   3  
  14 ccc 0.76255108   4  
  15 ccc 0.88216552   5  
  </code></pre>
  <p>What would be a good way to do this?</p>