title: Stata: save residuals from regressions by group in a single variable
body: <p>In Stata I want to run multiple regressions by group and save the corresponding residuals in a single variable. This is a working example of what I'm trying to do:</p>
  
  <pre><code>sysuse auto, clear
  
  forvalues i=0/1 {
  regress price mpg if foreign==`i'
  predict r_`i' if foreign==`i', resid
  }
  
  egen residuals=rowtotal(r_0-r_1) , missing
  drop r_0-r_1
  </code></pre>
  
  <p>While the above loop works just fine, my guess is that there must exist a more elegant way to achieve this? </p>