如何在Stata中生成记录截至当前时间最高酒精等级的变量
解决方案:生成患者累积最高酒精等级变量
要实现你需要的highestsofar变量,核心是对每个患者的时序数据计算截至当前年份的累积最高酒精等级。在Stata里可以用内置的累积最大值函数快速实现,步骤如下:
完整代码
* 加载原始数据(如果尚未加载) clear input long patid float(year cohort) 1051 1994 1 2051 1972 1 2051 1989 2 2051 1990 2 2051 2000 2 2051 2001 3 2051 2002 1 2051 2003 2 8051 1995 1 8051 1996 1 8051 2003 1 end label values cohort cohortlab label define cohortlab 0 "general population" 1 "no alcohol data" 2 "indeterminate" 3 "lifetime_abstainer" 4 "low_risk" 5 "hazardous" 6 "AUD" , replace * 生成累积最高等级变量 bysort patid (year): gen highestsofar = cummax(cohort) * 给新变量同步标签 label values highestsofar cohortlab * 查看最终结果 list patid year cohort highestsofar, clean
代码逻辑说明
- 分组排序:
bysort patid (year)先按患者ID分组,同时确保每组内的观测值按年份从小到大排序——这是计算累积值的关键前提,保证时序逻辑的正确性。 - 累积最大值计算:
cummax(cohort)是Stata内置的累积最大值函数,会在每个患者的分组内,逐行计算从第一行到当前行的cohort最大值,完美匹配“截至对应年份时出现过的最高酒精等级”需求。 - 标签同步:
label values highestsofar cohortlab让新变量和原cohort使用完全相同的标签,方便后续数据解读和可视化。
最终结果验证
运行代码后,你会得到和目标数据集完全一致的输出:
patid year cohort highestsofar 1051 1994 1 1 2051 1972 1 1 2051 1989 2 2 2051 1990 2 2 2051 2000 2 2 2051 2001 3 3 2051 2002 1 3 2051 2003 2 3 8051 1995 1 1 8051 1996 1 1 8051 2003 1 1
内容的提问来源于stack exchange,提问作者Abdul-Kareem Abdul-Rahman
相关产品推荐
相关产品推荐

