xingxf 发表于 2013-5-2 21:26 
Nick的办法还是有启发的
Another tip from Michael Barker (Statalist)
-----------------------------------------------------------------
It looks like you are comparing each observation to every other observation in your data set. If your data are sorted, you only have to look back within each 5-year window for each id. If your data are sorted descending by date, the code would look like this:
gen temp = flag
local N = _N
forvalues i = 1(1)`N' {
local j=`i'+1
while (id[`i']==id[`j'] & (date[`i'] - date[`j'])/365.25 <= 5) {
replace temp = temp[`i'] + temp[`j'] in `i'
local j = `j'+1
}
}
If your data were sorted ascending by date, you would just iterate j
downwards (j = i-1, j=j-1) and start the "forvalues" loop at 2
(forvalues 2(1)`N' {)
-----------------------------------------------------------------
上面程序中的flag相当于你源数据中的B,temp为你要生成的变量。你可以在这里查看完整的回复
http://www.stata.com/statalist/archive/2013-05/msg00087.html