Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Storing mean/scalar in a loop

    Hi. I am analyzing a set of data and would like to know the weighted average age of observations in each state. I am having trouble writing a loop that correctly and effectively incorporates the idiosyncratic weights. For instance, I want to do the following:
    mean weight if state==1
    *store this weight somehow as weight_state1
    gen weighted_age=weight*age/weight_state1 if state==1
    mean weighted_age
    *I want to do this for all states

    I have been doing this for binary variables such as sex. I used:
    mean weight if sex==1
    *output is, for example, 5000
    gen weighted_age_male=weight*age/5000 if sex==1
    mean weighted_age_male

    But to do this for all states is a monumental task (because there are variables other than age I want to analyze) and I'm sure there is an easier way to do it in a loop. So far, I know that I can do summ and svret to store the scalars (including the mean) into a table, but I don't know how to extract that one number to use in the next line of code...

    Any help is appreciated!

  • #2
    Read -help egen- and -help by- to learn about these very useful parts of Stata. Specificaly:


    Code:
    by state, sort: egen mean_state_weight = mean(weight)
    
    foreach v of varlist age { // AND LIST THE OTHER VARIABLES AFTER age
        by state: egen mean_weighted_`v' = mean(weight*`v'/mean_state_weight)
    }

    Comment


    • #3
      Originally posted by Clyde Schechter View Post
      Read -help egen- and -help by- to learn about these very useful parts of Stata. Specificaly:


      Code:
      by state, sort: egen mean_state_weight = mean(weight)
      
      foreach v of varlist age { // AND LIST THE OTHER VARIABLES AFTER age
      by state: egen mean_weighted_`v' = mean(weight*`v'/mean_state_weight)
      }
      Thank you for directing me to these very helpful commands that solved my problem!

      Comment

      Working...
      X