title: Mimicking _n in Stata to generate a dummy variable in R
body: <p>I have a dataset which looks like this: </p>
  
  <pre><code>fact_code style_serial
  1004      style_101
  1004      style_101
  1004      style_101
  1004      style_102
  1004      style_102
  1004      style_102
  5002      style_101
  5002      style_101
  5002      style_101
  5002      style_102
  5002      style_102
  5002      style_102
  </code></pre>
  
  <p>where <code>fact_code</code> is the factory code, and <code>style_serial</code> is the serial number of the garment style that the factory produces. What I am trying to generate, is a variable, <code>ss</code>, that looks like this:</p>
  
  <pre><code>fact_code style_serial ss
  1004      style_101    1
  1004      style_101    0
  1004      style_101    0
  1004      style_102    1
  1004      style_102    0
  1004      style_102    0
  5002      style_101    1
  5002      style_101    0
  5002      style_101    0
  5002      style_102    1
  5002      style_102    0
  5002      style_102    0
  </code></pre>
  
  <p>Basically, this variable, <code>ss</code>, can be generated by the Stata code as follows: </p>
  
  <pre><code>bysort fact_code style_serial: gen ss=_n==1
  </code></pre>
  
  <p><code>_n</code> is Stata notation for the current observation number. </p>
  
  <p>But I am trying to generate the same dummy variable, <code>ss</code>, using R but keep getting errors. These are the R codes that I have tried to mimic the above Stata code:</p>
  
  <pre><code>mydf &lt;- mydf %&gt;% 
    group_by(fact_code, style_serial) %&gt;% 
    mutate(ss = n_distinct(fact_code, style_serial))
  </code></pre>
  
  <p>and </p>
  
  <pre><code>mydf &lt;- mydf %&gt;% group_by(fact_code, style_serial) %&gt;% 
    mutate(ss =  ave(mydf$fact_code, mydf$style_serial, FUN = seq_along))
  </code></pre>
  
  <p>The name of the R dataframe is <code>mydf</code>. </p>
  
  <p>Any help would be appreciated. </p>