0 matrix montecarlo simulate stata
我想用置信区间计算我的数据中的一组组的总结统计数据(例如年龄,性别).为此,我使用泊松分布中的蒙特卡罗模拟绘图值来获取数据中的每一行,然后折叠行以获得摘要.整个手术过程工作正常,如果模拟的结果(使用rclass返回标)只是一个值,但只要我尝试模拟多个结果(使用ereturn中的eclass矩阵),它是不工作(见下面的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
Run Code Online (Sandbox Code Playgroud)
关键的是,你可以返回矩阵中的e(b)使用ereturn post,在这种情况下,你可以使用短切_b的simulate.
除此之外我稍微清理了一下代码:你不需要按_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
Run Code Online (Sandbox Code Playgroud)