错误:'没有定义变量'在使用蒙特卡罗模拟时的stata

时间:2015-02-23 17:55:12

标签: stata montecarlo

我编写了下面的程序,并不断收到错误消息,说明我的变量未定义。

有人可以看看错误在哪里以及我应该如何调整代码?真的没什么用。

program define myreg, rclass
drop all

set obs 200
gen x= 2*uniform()
gen  z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y  x z
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y x z
more
return scalar b0 =_[_cons]
return scalar b1=_[x]
return scalar b2 =_[z]
more
end

simulate b_0 = r(b0) b_1 = r(b1) b_2 = r(b2), rep(1000): myreg

1 个答案:

答案 0 :(得分:1)

*A possible solution with eclass

capture program drop myreg
program define myreg, eclass 
 * create an empty data by dropping all variables
 drop _all

set obs 200
gen x= 2*uniform()
gen z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e  /*to get r(mean) you need to run sum first*/
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y  x z
end
*gather the coefficients (_b) and standard errors (_se) from the *regression each time
simulate _b _se, reps(1000) seed (123): myreg
* show the final result 
mat list  r(table)

* A possible solution with rclass
* To understand the difference between rclass and eclass, see the Stata manual(http://www.stata.com/manuals13/rstoredresults.pdf)

capture program drop myreg
program define myreg, rclass
drop _all

set obs 200
gen x= 2*uniform()
gen z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y  x z

mat output=e(b)
return scalar b0=output[1,3]
return scalar b1=output[1,1]
return scalar b2=output[1,2]
end
simulate b_0=r(b0) b_1=r(b1) b_2=r(b2), rep(1000) seed (123): myreg
return list

* P.S。您应该阅读@Nick建议的所有评论,以完全理解我在这里所做的事情。 。