简体   繁体   中英

Loop and calculate average in Stata

I am trying to calculate the Gini coefficient as the average over five repetitions. My code doesn't correctly work, and I cannot find a way to do it.

inequal7 is a user-written command.

gen gini=.
forval i=1/5 {
    mi xeq `i' : inequal7 income [aw=hw0010]
    gen gini_`i'=.
    scalar gini_`i'  = r(gini)
    replace gini_`i'= r(gini)
    if `i' ==5 {
        replace gini = sum(gini_1+gini_2+gini_3+gini_4+gini_5)/5
    }
}

Can someone help me?

There is no context on or example of the dataset you're using. This may not work but it's likely to be closer to legal and correct than what you have.

scalar gini = 0 
forval i=1/5 {
    mi xeq `i' : inequal7 income [aw=hw0010]
    scalar gini  = scalar(gini) + r(gini)
}
scalar gini = scalar(gini) / 5 

Notes:

  1. Using variables to hold constants is legal, but not necessarily good style.

  2. sum() gives the running or cumulative sum; applied to a variable that's a constant it does far more work than you need, and at best the correct answer will just be that in observation 1. As you're feeding it the sum of 5 values, it's redundant any way.

  3. Watch out: names for scalars and variables occupy the same namespace.

If this is a long way off what you want, and you get no better answer, you're likely to need to give much more detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM