简体   繁体   English

在Stata中循环并计算平均值

[英]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. inequal7是用户编写的命令。

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; 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.应用于一个常量的变量,它所做的工作比您需要的要多得多,而正确的答案充其量只是观察 1 中的那个。当您给它提供 5 个值的总和时,它无论如何都是多余的。

  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.如果这与您想要的相去甚远,并且您没有得到更好的答案,那么您可能需要提供更多细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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