问题
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'
}
You need to use a command
generate
to produce a new variable.You need to reference local macro values with quotation marks.
egen
has its ownmean()
function, but it produces a variable, whereas you need a constant here. Usingsummarize, meanonly
is the most efficient method. There is in Stata nomean()
function that can be applied anywhere. Once you usesummarize
, there is no need to use a local macro to hold its results. Herer(mean)
can be used directly.You have
>=
twice, but presumably don't mean that. Usinginrange()
is not essential in writing your condition, but gives shorter code.You can't use
if
qualifiers to qualify assignment oflocal
macros in the way you did. They make no sense to Stata, as such macros are constants.longitbirthqtr
looks like a quarterly date. Hence I didn't use the namecurrent_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