数据如下所示:
id year month mtgrowth
106 2008 12 -.189898
106 2008 11 .062838
106 2008 10 -.017981
106 2008 09 -.036235
106 2008 08 .04701
106 2008 07 -.129576
106 2008 06 .14934
106 2008 05 -.109805
106 2008 04 -.122462
106 2008 03 .036118
106 2008 02 .065664
106 2008 01 .135678
106 2007 12 .003024
106 2007 11 .146291
106 2007 10 .079591
107 2008 04 .051582
107 2008 03 .023223
107 2008 02 .047935
107 2008 01 -.005136
107 2007 12 .034928
107 2007 11 -.046343
对每个id,特定年份月份,求其前12个月mtgrowth的之和。比如对于106,在2008年12月,对2007年12月至2008年11月的mtgrowth之和;对于106,在2008年11月,对2007年11月至2008年10月的mtgrowth之和;对于106,在2008年11月,对2007年10月至2008年09月的mtgrowth之和;对于106,在2008年10月,对2007年09月至2008年08月的mtgrowth之和,但由于2007年09月缺失,故该求和值也缺失。用同样的方法,求id=107的各值。
gen mtg = .
forvalues i=2007/2008{
forvalues j=1/12{
by code, sort: egen mtg_`i'_`j' = sum(mtgrowth) if year==`i' & month<`j' & month>`j'-13
replace mtg = L.mtg_`i'_`j' if year==`i' & month==`j'
}
}
有两个疑问:
1) 当取滞后时,需要xtset,但直接用xtset id week并不对;
2) 这种求法只能求同一年内,不能跨年求和。
由于数据集很大,总样本数达到5-6万个,所以必须用循环语句。此外,数据非平衡面板,即有些有2006.03-2008.12,而有些则是2007.06-2008.09。。
谢谢各位高手啦!!