【问题标题】:if statement in egen based on current observation and other observations in group (to calculate moving average)egen 中的 if 语句基于当前观察和组中的其他观察(计算移动平均值)
【发布时间】:2016-01-08 01:29:58
【问题描述】:

假设我有由此生成的数据:

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]

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

在我的错误代码行中,在第一个 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)

【问题讨论】:

  • 快速建议:从help egen 开始,我们有“显式下标(使用_N 和_n),通常与generate 一起使用,不应与egen 一起使用”。

标签: average stata moving-average


【解决方案1】:

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

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)

【讨论】:

  • 效果很好!次要的一点,但为了符合我的描述(我想取今年和前 3 年的移动平均线),我认为最后一行代码应该是 tsegen avg = rowmean(L(0/3).y) 而不是 tsegen avg = rowmean(L(0/2).y)
猜你喜欢
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多