title: How can I label categories sequentially by group in R?
body: <p>This is a very simple problem, but I have the following data:</p>
  
  <pre><code>&gt; head(Session_numbers)
     ID Session 
  1  1 1_43392 
  2  1 1_43392 
  3  1 1_43392 
  4  1 1_43394 
  5  1 1_43394 
  6  1 1_43394 
  7  1 1_43398 
  8  1 1_43401 
  9  2 2_44502 
  10 2 2_44502 
  </code></pre>
  
  <p>where ID is the grouping label per subject, and every row has a session code, which corresponds to points in time. I want to number the session codes sequentially in a variable 'Snum' so that each identical session code per ID gets grouped and is given the same number, such as: </p>
  
  <pre><code>   ID Session Snum
  1  1 1_43392 1
  2  1 1_43392 1
  3  1 1_43392 1
  4  1 1_43394 2
  5  1 1_43394 2
  6  1 1_43394 2
  7  1 1_43398 3
  8  1 1_43401 4
  9  2 2_44502 1
  10 2 2_44502 1
  </code></pre>
  
  <p>The number of Sessions per ID differs, and every Session code is unique. </p>
  
  <p>I have tried to use <code>ave</code>, <code>dplyr</code> and <code>data.table</code> but I just can't seem to get it right, e.g.:</p>
  
  <pre><code> DT &lt;- data.table(Session_numbers)
   DT[, Snum := seq_len(.N), by = list(ID, Session)]
  
   &gt; head(DT)
      ID Session Snum
   1:  1 1_43392    1
   2:  1 1_43392    2
   3:  1 1_43392    3
   4:  1 1_43394    1
   5:  1 1_43394    2
   6:  1 1_43394    3
  </code></pre>
  
  <p>Or using <code>dplyr</code>, with the following code which gives me an error message:</p>
  
  <pre><code>&gt; Session_numbers %&gt;%
   +   group_by(ID, Session) %&gt;%
   +   mutate(Snum = row_number())
   Error: row_number() should only be called in a data context
   Call `rlang::last_error()` to see a backtrace
  </code></pre>
  
  <p>or with <code>ave</code></p>
  
  <pre><code>head(Session_numbers)
    ID Session num
  1  1 1_43392   1
  2  1 1_43392   2
  3  1 1_43392   3
  4  1 1_43394   1
  5  1 1_43394   2
  6  1 1_43394   3
  </code></pre>
  
  <p>My question is similar to this one: <a href="https://stackoverflow.com/questions/7450600/count-number-of-observations-rows-per-group-and-add-result-to-data-frame">Count number of observations/rows per group and add result to data frame</a></p>
  
  <p>What am I missing?</p>