错误:使用蒙特卡洛模拟时,Stata中的“未定义变量" [英] Error:'no variables defined' in stata when using monte carlo simulation

查看:1057
本文介绍了错误:使用蒙特卡洛模拟时,Stata中的“未定义变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在下面编写了程序,并不断收到错误消息,提示我的变量未定义.

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

推荐答案

*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建议的所有评论,以完全了解我在这里所做的事情. .

*P.S. You should read all the comments as suggested by @Nick to fully understand what I did here. .

这篇关于错误:使用蒙特卡洛模拟时,Stata中的“未定义变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆