【问题标题】:Error:'no variables defined' in stata when using monte carlo simulation错误:使用蒙特卡罗模拟时在 stata 中“未定义变量”
【发布时间】:2015-02-23 17:55:11
【问题描述】:

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

有人可以看看错误在哪里以及我应该如何调整代码吗?似乎真的没有任何效果。

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

【问题讨论】:

  • e=e-r(mean) 在这里是非法的。这也是多余的,因为replace 会这样做。但是除非你在运行它之前做了一个summarize,否则没有r(mean)可以使用,所以e最终会全部丢失。风格上的一点是,如果您的 Stata 允许 rnormal() 它允许 runiform() 并且您不需要使用旧的函数名称来生成随机数。
  • drop all 删除一个名为 all 的变量(如果存在)。你的意思可能是drop _all
  • 程序中的第一个regress 是没有意义的,因为你从不使用它的结果。如果你认为r(mean)regress 留下的,那就大错特错了。
  • 第二个gen 将失败,因为y 已经存在。
  • 这似乎与(例如)stackoverflow.com/questions/28674482/… stackoverflow.com/questions/28674405/… 有关如果同一个人在幕后,如果它们不再是最新的并且没有答案,请删除您的问题。论坛上充斥着失败的帖子,这不符合任何人的利益。

标签: stata montecarlo


【解决方案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

*附注您应该按照@Nick 的建议阅读所有 cmets,以完全理解我在这里所做的事情。 .

【讨论】:

  • 指标:这很有帮助。我暂时将我的 cmets 留在原处,因为他们解释了 OP 代码的一些问题。在极限情况下,如果你为他们编写程序,发帖者可能学不到太多东西。欢迎您将我的任何 cmets 复制到您的答案中;我将删除任何如此复制的内容。
  • 尼克:我认为你不需要删除你的 cmets。这些是有效的 cmets,应该对 OP 有所帮助。
  • 谢谢,但它们也可以或更好地融入您的答案。如果您想添加更多的 cmets,那就更好了。我担心这些线程不仅仅是在公共场合获得个人帮助的人。为了对其他人有用,解释是有帮助的。
  • 尼克:谢谢。我根据您的建议添加了一些细节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 2012-04-26
  • 2015-02-10
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
相关资源
最近更新 更多