title: Stata: ignore missing values when counting
body: <p>I'd like to create a variable (<em>counter</em>) which counts non-missing values of another variable (<em>firmage0</em>) in every year. My code looks like this:</p>
  
  <pre><code>sort year  
  quietly by year: gen counter = _n if firmage0 != . 
  </code></pre>
  
  <p>Unfortunately, Stata starts counting with 1 even if there are missing values. But I'd like to start counting when there is a non-missing value. In addition the second nonmissing value should have the value "2", the third "3" and so on. There is one important restriction. Don't use <strong>preserve</strong> and <strong>restore</strong>! After creating the variable <em>counter</em>, my dataset looks like this (this is only a small part of it). Free space means missing value!</p>
  
  <pre><code>year    firmage0    counter
  1975        
  1975        
  1975        
  1975        
  1975    21  5
  1975        
  1975    60  7
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975    115 20
  1975        
  1975        
  1975
  </code></pre>
  
  <p>But the dataset should look like this:</p>
  
  <pre><code>year    firmage0    counter
  1975        
  1975        
  1975        
  1975        
  1975    21  1
  1975        
  1975    60  2
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975        
  1975    115 3
  1975        
  1975        
  1975    
  </code></pre>