When I try to create a variable in Stata with a loop, I want the resulting variable's values to exist in the order in which the loop was run, but instead, the results are in numeric ascencinding order. How can I fix this?
For example, I want to create a variable that shows the average number of children a woman had over 5 survey waves by race (shown here as `k'). Below I have a loop for Black women [race_eth ==3].
forvalues k = 1/5 {
summarize numkids [w=weightvar] if race_eth == 3 & survey == `k', detail
replace wtmn_numkids_black = r(mean) if race_eth == 1 & survey == `k'
}
I want the resulting variable to show me the values in order of survey year (which is the order in which the loop occurred), so the first value should be survey 1, second should be survey 2, etc. But instead, Stata orders the values from lowest to highest, creating a variable that looks like this:
wtmn_numkids_black -- Svy weighted mean of number of children - black
----------------------
Freq.
2.487754
2.547431
2.686026
2.797447
2.999271
Any help is much appreciated!
For example, I want to create a variable that shows the average number of children a woman had over 5 survey waves by race (shown here as `k'). Below I have a loop for Black women [race_eth ==3].
forvalues k = 1/5 {
summarize numkids [w=weightvar] if race_eth == 3 & survey == `k', detail
replace wtmn_numkids_black = r(mean) if race_eth == 1 & survey == `k'
}
I want the resulting variable to show me the values in order of survey year (which is the order in which the loop occurred), so the first value should be survey 1, second should be survey 2, etc. But instead, Stata orders the values from lowest to highest, creating a variable that looks like this:
wtmn_numkids_black -- Svy weighted mean of number of children - black
----------------------
Freq.
2.487754
2.547431
2.686026
2.797447
2.999271
Any help is much appreciated!

Comment