首页 文章

回归循环和存储系数

提问于
浏览
0

我将(1)多次循环回归某个标准; (2)从每个回归中存储一定的系数 . 这是一个例子:

clear
sysuse auto.dta
local x = 2000
while `x' < 5000 {
      xi: regress price mpg length gear_ratio i.foreign if weight < `x'
      est sto model_`x'
      local x = `x' + 100
}
est dir

我只关心一个预测器,比如 mpg . 我想从每个结果中提取 mpg 的系数到一个独立的文件(任何文件都可以, .dta 会很棒),看看是否有一个趋势,因为 weight 的阈值增加了 . 我现在正在做的是使用 estout 导出结果,如:

esttab * using test.rtf, replace se stats(r2_a N,  labels(R-squared)) starl(* 0.10 ** 0.05 *** 0.01) nogap onecell title(regression tables)

estout 将导出所有内容,我需要编辑结果 . 这适用于几乎没有预测变量的回归,但我的真实数据集有超过30个变量,回归将循环至少100次(我有一个变量 Distance ,范围从0到30,000:它在示例中的角色为 weight ) . 因此,我很难在不犯错误的情况下编辑结果 .

有没有其他有效的方法来解决我的问题?因为我的情况不是循环一个组变量,而是超过一定的标准 . statsby 函数似乎在这里运行不佳 .

2 回答

  • 1

    正如@Todd已经建议的那样,您可以选择您关注的特定结果,并使用 postfile 将它们存储为新数据集中的新变量 . 请注意, forval 循环比 while 代码更直接,而使用 xi: 在最近版本的Stata中被因子变量表示法取代 . (我没有改变,以防您使用的是旧版本 . )请注意保存结果的评估,例如 _b[_cons] ,并使用括号 () 来停止评估负面符号 . 其他地方的一些代码示例暂时将结果存储在本地宏或标量中,这是非常不必要的 .

    sysuse auto.dta, clear 
    tempname myresults 
    postfile `myresults' threshold intercept gradient se using myresults.dta 
    quietly forval x = 2000(200)4800 {
        xi: regress price mpg length gear_ratio i.foreign if weight < `x'
        post `myresults' (`x') (`=_b[_cons]') (`=_b[mpg]') (`=_se[mpg]') 
    }
    postclose `myresults' 
    use myresults 
    list 
    
         +---------------------------------------------+
         | thresh~d   intercept    gradient         se |
         |---------------------------------------------|
      1. |     2000    -3699.55   -296.8218   215.0348 |
      2. |     2200   -4175.722   -53.19774   54.51251 |
      3. |     2400   -3918.388   -58.83933   42.19707 |
      4. |     2600   -6143.622   -58.20153   38.28178 |
      5. |     2800   -11159.67   -49.21381   44.82019 |
         |---------------------------------------------|
      6. |     3000   -6636.524   -51.28141   52.96473 |
      7. |     3200   -7410.392   -58.14692   60.55182 |
      8. |     3400   -2193.125   -57.89508   52.78178 |
      9. |     3600   -1824.281   -103.4387   56.49762 |
     10. |     3800   -1192.767   -110.9302    51.6335 |
         |---------------------------------------------|
     11. |     4000     5649.41   -173.9975   74.51212 |
     12. |     4200    5784.363   -147.4454   71.89362 |
     13. |     4400     6494.47   -93.81158   80.81586 |
     14. |     4600     6494.47   -93.81158   80.81586 |
     15. |     4800    5373.041   -95.25342   82.60246 |
         +---------------------------------------------+
    

    statsby (一个命令,而不是一个函数)根本就不是为这个问题设计的,所以它不是一个问题,它是否运作良好 .

  • 1

    我建议您查看 help postfile 以获取如何聚合结果的示例 . 我同意 statsby 可能不是最好的方法 . 在 price 上评估 mpgweight 之间的互动可能有助于解决似乎是一个经典的互动问题 .

相关问题