Combing/Collapsing 二进制变量按 SAS 中的患者 ID 排成一行

Combing/Collapsing binary variables into a single row by patient ID in SAS

我正在尝试将我的多行二进制变量折叠为每个患者 ID 的一行,如我的插图所示。有人可以帮我用 SAS 代码来做到这一点吗?谢谢

更新技巧

data want;
update have(obs=0) have;
by id;
run;

proc sql;
create table want as
select ID, max('2018'n) as Y2018, max('2019'n) as Y2019, max('2020'n) as Y2020
from have
group by ID
order by ID;
quit;

未经测试,因为您以图像形式提供数据,请post作为文本,最好作为数据步骤。

这是一个基于数据步骤的解决方案。当然比上面的答案更复杂,但它确实展示了使用数组、first.last. 处理以及 retain 语句的方法。

使用保留的临时数组来保存2018-2020的值,直到每个id组的最后一次观察。在每个 id 的最后一个值上,检查每个持有的值是否为 1,并将年份的每个值设置为 1 或 0。

data want;
    set have;
    by id;

    array year[3] '2018'n--'2020'n;
    array hold[3] _TEMPORARY_;
    retain hold;

    if(first.id) then call missing(of hold[*]);

    do i = 1 to dim(year);
        if(year[i] = 1) then hold[i] = 1;
    end;

    if(last.id) then do;
        do i = 1 to dim(year);
            year[i] = (hold[i] = 1);
        end;

        output;
    end;

    drop i;

run;

如果规则是将它设置为 1,如果它是 1,则取 MAX。如果规则是仅当所有项都为一时才将其设置为一,则取 MIN。

proc summary data=have nway ;
  by id;
  output out=want max= ;
run;