Stata双观测个体数据集重排及基线-随访变量提取回归实现
分步骤实现Stata数据集重构与回归模型搭建
一、目标数据集重构(无需手动拆分奇偶行)
依靠个体唯一标识rescode匹配两个时点的观测信息,全程Stata可自动化完成:
- 先校验数据结构,确认每个
rescode仅对应2条带时间标签的观测:
输入命令isid rescode followup,如果无报错即代表数据结构符合预期 - 分别提取两个时点的有效观测:
- 提取基线时点的所有控制变量、基线核心自变量,重命名避免和随访变量重名:
preserve keep if followup == "Baseline" // 注意核对数据中该变量的实际取值拼写,不要出现匹配偏差 keep rescode enterprise aimag group loan_baseline eduvoc edusec age16 under16 marr_cohab age age_sq buddhist hahl sep_f nov_f soum rename enterprise enterprise_baseline tempfile base_obs save `base_obs' restore- 提取随访时点的目标因变量:
preserve keep if followup == "Followup" // 注意原命令中将Followup错拼为Folowup,属于之前命令无法运行的核心拼写错误 keep rescode enterprise rename enterprise enterprise_followup tempfile fol_obs save `fol_obs' restore - 按唯一标识匹配合并两个时点的观测,得到单个体单行的分析数据集:
运行完成后即可得到611行的专用分析数据集,无需手动识别、拆分奇数/偶数行。merge 1:1 rescode using `base_obs' keep if _merge == 3 // 仅保留两个时点都匹配成功的611个个体 drop _merge
对应菜单操作路径:依次点击Data > Create or change data > Other file-transformation commands > Reshape,选择长转宽模式,个体标识选rescode、时变标识选followup,需要转宽的变量选enterprise,点击确认即可自动完成等价的数据集转换。
二、修正原有回归命令的适配问题
原命令无法正常运行的核心原因是两个语法硬伤:
- 不支持在回归变量列表中嵌入if筛选语句,即
enterprise(if followup="xxx")的写法Stata无法识别 - 存在拼写错误,将
Followup错写为Folowup,即使语法正确也无法匹配到对应观测
因为经过数据集重构后,基线核心自变量、随访因变量已经作为独立变量存在于同一条个体观测上,直接调用即可,修正后的回归命令为:
reg enterprise_followup i.aimag group loan_baseline eduvoc edusec age16 under16 marr_cohab age age_sq buddhist hahl sep_f nov_f enterprise_baseline, vce(cluster soum)
操作提示:
- 所有数据集重构操作前,先保存备份原始数据,避免不可逆的操作失误
- 运行完数据集合并后,通过
list rescode enterprise_baseline enterprise_followup in 1/10核对变量取值匹配是否正确,避免出现时点错配 - 因
enterprise为二值因变量,后续可根据分析需求将reg替换为logit或probit,命令结构保持完全一致
内容的提问来源于stack exchange,提问作者Hans
相关产品推荐
相关产品推荐

