2016-10-22 252 views
0

我有变量y,x1x2。我使用reg d.(y x1 x2), nocons来估计一个差分方程(没有截距)。现在我想用估计的系数得到原始变量的残差。我可以做到Stata - 如何使用差分方程的估计值获得原始方程的残差

reg d.(y x1 x2), nocons 
matrix b = e(b) 
gen resid = y - b[1,1]*x1 - b[1,2]*x2 

但是会有更简单的方法吗?我需要保留这些生成的残差以供将来使用。这是一个完整的小例子。

clear all 
set obs 100 
gen id = floor((_n-1)/5)+1 
by id, sort: gen year = 1990+_n 
xtset id year 
set seed 1 
gen x1 = rnormal() 
gen x2 = rnormal() 
gen y = rnormal() 
*** Data generated *** 
reg d.(y x1 x2), nocons 
matrix b = e(b) 
gen resid = y - b[1,1]*x1 - b[1,2]*x2 

我不知道是否有一个灵活的方法,因为有时我想彻底改变变量名的回归(例如,reg dy dx1 dx2, nocons不仅仅是reg d.(y x1 x2))。我想也许predict可能有帮助,但我不知道。是否有可能避免显式输入变量名称?

回答

1

predict将不起作用,因为它会在差异规模上创建残差。你需要原始y的残差,这是不寻常的,所以没有现成的解决方案。

我认为最简单的途径就是做这样的事情:

reg d.(y x1 x2), nocons coefl 
local vars:colnames e(b) // get a list of coefficients 
foreach x of local vars { 
    local xvar = subinstr("`x'","D.","",1) // strip out the D. prefix from the coefficient names 
    local diff "`diff' - _b[`x']*`xvar'" 
} 
gen resid = y `diff' 

如果你有一个像DX1和DX2协变量,你可以修改前缀stipper这样的:

local xvar = subinstr("`x'","d","",1) // strip out the first d prefix