【问题标题】:Monte Carlo simulation of a whole matrix in Stata在Stata中对整个矩阵进行蒙特卡罗模拟
【发布时间】:2014-04-24 12:42:22
【问题描述】:

我想用置信区间计算我的数据(例如年龄、性别)中的一组组的汇总统计量。为此,我使用蒙特卡罗模拟从泊松分布中为数据中的每一行绘制值,然后折叠这些行以获得摘要。如果模拟结果只是一个值(使用 rclass 中的返回标量),则整个过程工作正常,但是一旦我尝试模拟多个结果(在 eclass 中使用 ereturn 矩阵),它就不起作用(参见下面的 Stata 代码)。我收到错误消息:“表达式中的类型不匹配错误:e(A)”。如何在没有更复杂循环等的情况下模拟整个向量甚至结果矩阵?

非常感谢! 弗雷德

program bootPGW, eclass
use "C:\Users\649007\Desktop\Demetriq_PWG_edu.dta", replace
gen id=_n
sort id
gen N=_N
by id: gen    DL2=floor(rpoisson(calung))
by id:gen     D02=floor(rpoisson(D0))
by id:gen     Dsmoking=floor(rpoisson(smoking))
by id:gen     ML2=(DL2/numpyr)*1000
by id:gen     AL2=(ML2-CPSIIrate)/ML2
by id:replace AL2=0 if AL2<0
by id:gen     A02=1-exp(-PWGcoef*(ML2-CPSIIrate))
by id:gen     A2=(AL2*DL2+A02*D02)/(DL2+D02)
gen Adeaths=totdeath*A2
collapse (sum) Adeaths=Adeaths totdeath=totdeath Dsmoking=Dsmoking, by(edu_3cat sex country year)
gen AF_PWG=Adeaths/totdeath
gen AF_simple=Dsmoking/totdeath
mkmat AF_PWG, matrix(A)
ereturn matrix A=A
end

simulate a=e(A), reps(1000) nodots seed(123): bootPGW 

【问题讨论】:

  • crossposted at:link 如果我们在 Stata 论坛中解决问题,我会在这里发布答案。

标签: matrix stata montecarlo simulate


【解决方案1】:

关键是你可以使用ereturn post返回e(b)中的矩阵,在这种情况下你可以使用simulate中的快捷方式_b

除此之外,我稍微清理了代码:您不需要通过 _n 来执行此操作,因为这与常规 generate 相同。您也不需要 floor() 周围的 rpoisson() 函数,因为它已经返回整数。您没有使用 N,因此您不需要它,但即使您这样做,您也可以更好地将其存储为本地宏(或者如果您更喜欢标量)而不是变量(数据集中的列),因为它是单个数字,因此将其存储在变量中只会浪费内存。

program bootPGW, eclass
    use "C:\Users\649007\Desktop\Demetriq_PWG_edu.dta", replace
    gen     DL2=rpoisson(calung)
    gen     D02=rpoisson(D0)
    gen     Dsmoking=rpoisson(smoking)
    gen     ML2=(DL2/numpyr)*1000
    gen     AL2=(ML2-CPSIIrate)/ML2
    replace AL2=0 if AL2<0
    gen     A02=1-exp(-PWGcoef*(ML2-CPSIIrate))
    gen     A2=(AL2*DL2+A02*D02)/(DL2+D02)
    gen Adeaths=totdeath*A2
    collapse (sum) Adeaths=Adeaths totdeath=totdeath Dsmoking=Dsmoking, ///
        by(edu_3cat sex country year)
    gen AF_PWG=Adeaths/totdeath
    gen AF_simple=Dsmoking/totdeath
    mkmat AF_PWG, matrix(A)
    ereturn post A
end

simulate _b, reps(1000) nodots seed(123): bootPGW 

【讨论】:

  • 感谢马丁!这确实非常优雅。但我收到以下错误:conformability error an error occurred when simulate executed bootPGW r(503); 我猜 mkmat 的矩阵有问题?
  • A 需要是一个行向量,所以你可能需要重构矩阵 A。
  • 好的,它可以工作。我使用matrix B=A' 转置矩阵,然后使用ereturn post B 返回行向量B。虽然我仍然无法模拟整个矩阵,但模拟向量已经让生活变得更加轻松。非常感谢!
  • 顺便说一句,gen AF_simple=Dsmoking/totdeath 也是不必要的,因为它似乎没有做任何事情。
猜你喜欢
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 2012-04-26
相关资源
最近更新 更多