在bootstrap后粘贴观察中的标量值

时间:2013-10-16 14:09:28

标签: stata scalar

我需要帮助来粘贴自举系数及其下限和 在新变量中生成95%CI,以生成图表。

我尝试了下面的代码。它看起来像是检索到的标量 成功,但我无法将它们粘贴到具体的观察中 使用replace时。

clear all
forvalues j=0/1{
    foreach l in P2 P3 P4 {
        use `l'_per_`j', clear
        set seed 1
        reg estimate xaxis
        predict yhat
        gen yhat_bs=yhat
        gen ll_95per=.
        gen ul_95per=.
        local N = _N
        foreach i in 1/11 { //number of time periods to be predicted
            bootstrap pred=(_b[_cons] + _b[xaxis]*`i'), reps(1000) seed(1): reg
            estimate xaxis
            matrix b=e(b)
            scalar sb=b[1,1]
            matrix ci_normal=e(ci_normal)
            local par=b[1,1] //coefficient bootstrap
            local ll=ci_normal[1,1] //lower CI 95%
            local ul=ci_normal[2,1] //upper CI 95%
            replace yhat_bs=`par' if xaxis==`i' 
            replace ll_95per=`ll' if xaxis==`i' 
            replace ul_95per=`ul' if xaxis==`i'
        }
        save `l'_per_`j'_lin_trend, replace
    }
}

1 个答案:

答案 0 :(得分:1)

语法foreach i in 1/11在这里是错误的。就Stata而言,这是一个包含1/11项的列表,不会扩展。所以,当Stata到达行时

replace yhat_bs=`par' if xaxis==`i' 

将成为,这次循环执行一次,

replace <stuff> if xaxis==1/11 

现在这是合法的:1/11是Stata计算的分数。但是,没有xaxis的值等于该分数,因此没有任何内容被替换。

您想要foreach i of num 1/11甚至更好forval i = 1/11。这是对代码的重写。我还删除了不必要的中间宏和其他一些看似不必要的东西,但我还没有测试过。

clear all
forvalues j = 0/1 {
    foreach l in P2 P3 P4 {
        use `l'_per_`j', clear
        set seed 1
        reg estimate xaxis
        predict yhat
        gen yhat_bs = yhat 
        gen ll_95per = .
        gen ul_95per = .

        forval i = 1/11 { //number of time periods to be predicted
            bootstrap pred=(_b[_cons] + _b[xaxis]*`i'), reps(1000) seed(1): reg             estimate xaxis
            matrix b = e(b)
            matrix ci_normal = e(ci_normal)
            replace yhat_bs = b[1,1] if xaxis == `i' 
            replace ll_95per = ci_normal[1,1] if xaxis == `i' 
            replace ul_95per = ci_normal[2,1] if xaxis == `i'
        }
        save `l'_per_`j'_lin_trend, replace
    }
}