Stata中outreg2循环回归结果堆叠异常问题求助
问题分析与解决方案
你的代码无法生成预期的堆叠式表格,核心问题在于回归结果存储逻辑错误、循环顺序不合理,以及部分参数配置有误,具体问题和修正方案如下:
原代码存在的问题
- 未使用
eststo存储回归结果,每次直接调用outreg2写入文件,导致不同被解释变量的结果无法并列,只能追加在文件末尾。 ldep''宏未定义,ctitle()参数无法生成有效列标题,列标识混乱。- 循环顺序错误:先遍历被解释变量,再遍历x值,导致Y1的所有结果先输出,Y2的结果后续追加,无法形成同一x值对应“变量/Y1/Y2”的堆叠结构。
replace宏赋值逻辑有问题,后续调用outreg2时replace参数为空,可能导致文件写入异常。boottest中的变量名与回归模型不匹配:回归中使用的是treat,但boottest里写的是tr,会导致显著性检验报错。
修正后的代码
eststo clear * 定义被解释变量的列标题宏 local l_c3_family "Y1: c3_family" local l_c3_child "Y2: c3_child" * 先遍历x值(1/2/3),再遍历被解释变量,确保同一x的结果可并列 forvalues i = 1/3 { foreach dep of varlist c3_family c3_child { * 计算预处理均值(每个被解释变量仅需计算一次) if `i' == 1 { summarize `dep' if post == 0 & treat == 0 local mean_`dep' = string(r(mean), "%9.2f") } * 运行回归:限定treat为0或当前i值,使用三重交互项 qui: reg `dep' post##`i'.treat##dep_treated if inlist(treat, 0, `i'), vce(cluster intclu) * 对应变量名的boottest检验 boottest 1.post#`i'.treat#1.dep_treated, nograph boottype(wild) reps(1000) bootcluster(intclu) nonull level(90) * 用eststo存储结果,命名规则为x值+被解释变量 eststo model_`i'_`dep': qui reg `dep' post##`i'.treat##dep_treated if inlist(treat, 0, `i'), vce(cluster intclu) } } * 一次性输出堆叠表格到Word文件 outreg2 model_* using "results/2023_09_28_day_reg_ihs/T_spillovers_arms.doc", /// word replace bdec(3) sdec(4) nor2 nocons bracket /// keep(1.post#1.treat#1.dep_treated 1.post#2.treat#1.dep_treated 1.post#3.treat#1.dep_treated) /// ctitle(`l_c3_family' `l_c3_child') /// addstat("Pre-treatment mean", `mean_c3_family' `mean_c3_child') /// label
代码说明
- 宏定义:提前定义
l_c3_family和l_c3_child作为列标题,确保输出表格的列标识清晰。 - 循环顺序调整:先遍历x值(1/2/3),再遍历被解释变量,让同一x值的Y1、Y2回归结果被
eststo按组存储,方便后续并列输出。 - 预处理均值优化:仅在x=1时计算一次每个被解释变量的预处理均值,避免重复计算。
- eststo存储:用
model_i'_`dep''的规则命名存储的回归结果,确保后续outreg2能按x值和被解释变量正确分组。 - 统一输出:一次性调用
outreg2,通过keep()指定要显示的交互项,ctitle()设置两列的标题,addstat()添加预处理均值,最终生成“变量行-Y1结果-Y2结果”的堆叠式表格。
内容的提问来源于stack exchange,提问作者Will H.
相关产品推荐
相关产品推荐

