title: Count number of records and generate row number within each group in a data.table
body: <p>I have the following data.table</p>
  
  <pre><code>set.seed(1)
  DT &lt;- data.table(VAL = sample(c(1, 2, 3), 10, replace = TRUE))
      VAL
   1:   1
   2:   2
   3:   2
   4:   3
   5:   1
   6:   3
   7:   3
   8:   2
   9:   2
  10:   1
  </code></pre>
  
  <p><em>Within</em> each number in <code>VAL</code> I want to:</p>
  
  <ol>
  <li>Count the number of records/rows</li>
  <li>Create an row index (counter) of first, second, third occurrence et c. </li>
  </ol>
  
  <p>At the end I want the result</p>
  
  <pre><code>    VAL COUNT IDX
   1:   1     3   1
   2:   2     4   1
   3:   2     4   2
   4:   3     3   1
   5:   1     3   2
   6:   3     3   2
   7:   3     3   3
   8:   2     4   3
   9:   2     4   4
  10:   1     3   3
  </code></pre>
  
  <p>where "COUNT" is the number of records/rows for each "VAL", and "IDX" is the row index within each "VAL".  </p>
  
  <p>I tried to work with <code>which</code> and <code>length</code> using <code>.I</code>:</p>
  
  <pre><code> dt[, list(COUNT = length(VAL == VAL[.I]), 
               IDX = which(which(VAL == VAL[.I]) == .I))]
  </code></pre>
  
  <p>but this does not work as <code>.I</code> refers to a vector with the index, so I guess one must use <code>.I[]</code>. Though inside <code>.I[]</code> I again face the problem, that I do not have the row index and I do know (from reading <code>data.table</code> FAQ and following the posts here) that looping through rows should be avoided if possible. </p>
  
  <p>So, what's the <code>data.table</code> way? </p>