title: Counting rows in multiple variables using SAS
body: <p>I have a question in creating a count variable using SAS.  </p>
  
  <pre><code> Q R   
   ---- 
   1 a    
   1 a  
   1 b  
   1 b  
   1 b  
   2 a   
   3 a   
   3 c  
   4 c  
   4 c  
   4 c
  </code></pre>
  
  <p>I need to create a variable S that counts the rows that has same combination of Q and R.  The following will be the output.</p>
  
  <pre><code> Q       R       S
   -------------------  
   1       a       1  
   1       a       2  
   1       b       1  
   1       b       2  
   1       b       3*  
   2       a       1  
   3       a       1  
   3       c       1   
   4       b       1  
   4       b       2  
   4       b       3  
  </code></pre>
  
  <p>I tried using following program:</p>
  
  <blockquote>
    <p>data two;<br>
      set one;<br>
      S + 1;<br>
      by Q R;<br>
      if first.Q and first.R then S = 1;<br>
    run;</p>
  </blockquote>
  
  <p>But, this did not run correctly. For example, * will come out as 1 instead of 3. I would appreciate any tips on how to make this counting variable work correctly.</p>