egen 中的 if 语句基于当前观察和组中的其他观察(计算移动平均值)

if statement in egen based on current observation and other observations in group (to calculate moving average)

假设我有这样生成的数据:

clear all
set seed 100
set obs 36
egen group = seq(), from(1) to(2) block(18)
egen year = seq(), from(2000) to(2005) block(3)
egen month = seq(), from(1) to(3)
gen y = round(runiform()*10)
sort group month year
replace y = . in 3 
replace y = . in 7 
replace y = . in 11
replace y = . in 19
replace y = . in 28

出于说明目的,我们将重点关注前 6 个观察结果:

group   year    month   y
1       2000    1       10
1       2001    1       1
1       2002    1       
1       2003    1       9
1       2004    1       5
1       2005    1       6

我想做的是使用egen创建y的移动平均线。也就是说,取当年(含当年)前3年的平均值;如果年份不在数据中,则不要使用那一年。 2000 年的移动平均值为 10。我们想忽略计算中的遗漏;但只能追溯到 3 年前。对于年份 2005 对应的行,它将是 (20/3). For2004, it would be5(and not10/3`).

这里有一些不正确的代码来尝试解决这个问题。

bys group month: egen avg = mean(temp) if year>year[_n]-3 & year<=year[_n]

这会在所有地方产生缺失值。我想做的是为每个月的一天计算一个单独的数字,但是使用来自整个 bysort 组的数据,假设数据符合 3 年前的标准。

在我的错误代码行中,在第一个 group month 组中,我希望它从 obs 开始。 1。它应该计算年值大于 1997 且小于或等于 2000 的所有观测值的平均值。在这种情况下,它只是第一次观察。

然后进入观察2。它使用 2001 作为 year[_n] 的值,并根据前两个观察值计算平均值,因为它们符合条件。

我要描述的内容是否可以使用 egen?这是一个超越移动平均线应用的一般性问题。

此外,如果不可能,那么以下是否是计算移动平均线的最佳解决方案(再次只返回 3 年并忽略计算中的遗漏)?:

sort group month year
forvalues i = 1/3 {
    bys group: gen y_`i' = y[_n-`i']
}

bys group month: egen avg = mean(y) if year>year[_n]
egen ma_3 = rowmean(y y_1 y_2 y_3)

您可以使用 tsegen(来自 SSC)计算滚动 window 时间的统计数据。我不确定我是否理解您如何对观察结果进行分组,因为您有一个月份变量,但以下内容似乎可以满足您的需求:

clear all
set seed 100
set obs 36
egen group = seq(), from(1) to(2) block(18)
egen year = seq(), from(2000) to(2005) block(3)
egen month = seq(), from(1) to(3)
gen y = round(runiform()*10)
sort group month year
replace y = . in 3 
replace y = . in 7 
replace y = . in 11
replace y = . in 19
replace y = . in 28

* create a panel variable by grouping the group and month variable
isid group month year, sort
egen group_month = group(group month)

* declare data to be a time-series
tsset group_month year

* calculate a moving average over 3 years
tsegen avg = rowmean(L(0/2).y)