You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SAS Proc Summary按ID/MED保留附加变量并获取用药起止日期

问题:在Proc Summary中保留附加变量med_other

需求说明

需要从包含多名患者、多种药物的数据集中,获取每个患者-药物(ID/MED)组合的最早用药开始日期(start)与最晚用药结束日期(stop),同时保留med_other这类附加变量。

原始数据集(HAVE)

IDMEDstartstopmed_other
B12345863/23/20211/9/2022
B12345868/17/20211/9/2022
B12345862/10/20223/5/2023
B12345991/1/20202/15/2020someothermedname
B12345793/23/20211/9/2022
B12345794/20/20224/21/2022
B12345795/1/20224/30/2023
B12345796/8/20237/30/2024
A54321861/1/20191/3/2019
A54321862/5/20203/5/2020
A54321863/6/20204/6/2020
A54321501/1/20191/3/2019
A54321502/5/20203/5/2020
A54321503/6/20204/6/2020
A54321505/4/20205/5/2020
A54321505/10/20205/11/2020
A54321506/1/20208/30/2020
C98765256/8/202410/11/2024
C98765306/8/202412/1/2024
C98765306/9/202412/1/2024
C98765308/17/202412/31/2024
C98765301/1/20251/2/2025
C98765555/15/20205/30/2020
C98765554/15/20216/30/2022
C98765861/1/20192/1/2019
C98765863/1/20204/1/2020
C98765861/1/20242/1/2024
C98765863/1/20183/6/2018

期望结果

IDMEDstartstopmed_other
B12345863/23/20213/5/2023
B12345793/23/20217/30/2024
B12345991/1/20202/15/2020someothermedname
A54321861/1/20194/6/2020
A54321501/1/20198/30/2020
C98765306/8/20241/2/2025
C98765555/15/20206/30/2022
C98765863/1/20182/1/2024

现有尝试代码

以下代码能生成正确的start和stop,但丢失了med_other变量:

proc summary data=have nway ;
    class id med  ;
    var start stop;  
    output out=want min(start)=start max(stop)=stop ;
run;

解决方案

方法1:使用ID语句(推荐)

在proc summary中添加ID语句,指定需要保留的附加变量。该语句会保留变量值,且不会将其作为分组维度(前提是同一ID/MED组合内的med_other值一致,或你接受取组内第一条观测的变量值):

proc summary data=have nway;
    class id med;
    id med_other; /* 保留med_other变量 */
    var start stop;
    output out=want min(start)=start max(stop)=stop;
run;

方法2:将附加变量加入CLASS语句

如果同一ID/MED组合内的med_other值完全一致(要么全为空,要么是同一个非空值),可以将med_other加入CLASS语句,这样分组时不会拆分现有组合,同时保留该变量:

proc summary data=have nway;
    class id med med_other; /* 加入med_other作为分组变量 */
    var start stop;
    output out=want min(start)=start max(stop)=stop;
run;

方法3:使用Proc SQL实现(更灵活)

如果需要更灵活地处理med_other(比如提取组内非空值),可以用Proc SQL分组统计,直接保留变量:

proc sql;
    create table want as
    select 
        id, 
        med, 
        min(start) as start format=mmddyy10.,
        max(stop) as stop format=mmddyy10.,
        max(med_other) as med_other /* 取组内非空的med_other值 */
    from have
    group by id, med;
quit;

内容的提问来源于stack exchange,提问作者Carol-Ann Mullin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:33:12