Getting unknown function mean() in a forvalues loop

我们两清 提交于 2021-01-28 05:30:55

问题


Getting unknown function mean for this. Can't use egen because it has to be calculated for each value. A little confused.

edu_mov_avg=.
forvalues current_year =  2/133 {
    local current_mean = mean(higra) if longitbirthqtr >= current_year - 2  & longitbirthqtr >= current_year + 2
    replace edu_mov_avg = current_mean if longitbirthqtr = 
}

回答1:


Your code is a long way from working. This should be closer.

gen edu_mov_avg = .
qui forvalues current_qtr =  2/133 {
    su higra if inrange(longitbirthqtr, `current_qtr' - 2, `current_qtr' + 2), meanonly  
    replace edu_mov_avg = r(mean) if longitbirthqtr == `current_qtr' 
}
  1. You need to use a command generate to produce a new variable.

  2. You need to reference local macro values with quotation marks.

  3. egen has its own mean() function, but it produces a variable, whereas you need a constant here. Using summarize, meanonly is the most efficient method. There is in Stata no mean() function that can be applied anywhere. Once you use summarize, there is no need to use a local macro to hold its results. Here r(mean) can be used directly.

  4. You have >= twice, but presumably don't mean that. Using inrange() is not essential in writing your condition, but gives shorter code.

  5. You can't use if qualifiers to qualify assignment of local macros in the way you did. They make no sense to Stata, as such macros are constants.

  6. longitbirthqtr looks like a quarterly date. Hence I didn't use the name current_year.

With a window this short, there is an alternative using time series operators

tsset current_qtr 
gen edu_mov_avg = (L2.higra + L1.higra + higra + F1.higra + F2.higra) / 5 

That is not exactly equivalent as missings will be returned for the first two observations and the last two.

Your code may need further work if your data are panel data. But the time series operators approach remains easy so long as you declare the panel identifier, e.g.

tsset panelid current_qtr 

after which the generate call is the same as above.

All that said, rolling offers a framework for such calculations.



来源:https://stackoverflow.com/questions/18971326/getting-unknown-function-mean-in-a-forvalues-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!