title: Generating sums of variables with loops in Stata
body: <p>I'm having some problems with a loop that I'm trying to perform and probably with the syntax for generating the variable that I want.</p>
  
  <p>Putting in words, what I am trying to do make is a sum of a particular set of observations and storing each sum in a cell for a new variable. Here is an example of syntax that I used:</p>
  
  <p><code>forvalues j=1/50 {
  replace x1 = sum(houses) if village==</code>j'<code>&amp; year==2010
  }</code></p>
  
  <p><code>gen x2=.
  forvalues j=1/50 {
  replace x2 = sum(houses) if village==</code>j' <code>&amp; year==2011
  }</code></p>
  
  <p><code>gen x3 =.
  forvalues j=1/50 {
  replace x3 = sum(houses) if village==</code>j' <code>&amp; year==2012
  }</code></p>
  
  <p>This is from a dataset with more than 4000 observations. So, for each particular j, if I were successful with the code above, I would get an unique observation for each j (what I want to obtain), but I'm not obtaining this -- which is a sum of all houses, conditioned with the year and village; the total sum of houses per village in each year. I would greatly appreciate if someone could help me obtain one particular observation for each j in each variable.</p>