title: Stata. How to use if statement with sum()?
body: <p>I am trying to execute the following code:</p>
  
  <pre><code>    forval i = 1/51 {
  
      // number of households
      by hhid, sort: gen nvals = _n==1
      count if (nvals &amp; stateID == `i')
      local stateTotalHH = r(N)
  
          local avPersonHH`i' = sum(numper)/`stateTotalHH' if(nvals &amp; stateID ==`i')
          drop nvals 
  }
  </code></pre>
  
  <p>Everything works fine except <code>if</code> is not allowed with <code>sum()</code>. How can I estimate the total or the sum of all values in  <code>numper</code> variable for each state and at household level?</p>
  
  <p>ps: </p>
  
  <ol>
  <li>I cannot use <code>collapse numper, by(stateID)</code> because I have other estimations</li>
  <li>also, I cannot do the following: <code>duplicates drop hhid, force</code></li>
  </ol>