Error:'no variables defined' in stata when using monte carlo simulation

孤者浪人 提交于 2020-02-08 07:23:07

问题


I have written the program below and keep getting the error message that my variables are not defined.

Can somebody plese see where the error is and how I should adapt the code? Really nothing seems to work.

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:


*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. You should read all the comments as suggested by @Nick to fully understand what I did here. .



来源:https://stackoverflow.com/questions/28680167/errorno-variables-defined-in-stata-when-using-monte-carlo-simulation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!