我的数据集有 3 个变量,包括 ID、日期和注册,并且按 ID 和日期排序。我的目标是创建一个新的数据集,其中有另一个变量 enrol_flag,一旦 enroll 为 1,它应该为 1,但一旦 enroll 为 0,它应该变为 0 并保留该 0 值。
我正在使用 SAS 进行编程。
我的数据集看起来像:
ID Date enrol
1 01JAN21 0
1 O1FEB21 1
1 01MAR21 1
1 01APR21 1
1 01MAY21 0
1 01JUN21 0
1 01JUL21 1
1 01AUG21 1
2 01JAN21 1
2 O1FEB21 1
2 01MAR21 1
2 01APR21 1
2 01MAY21 1
2 01JUN21 0
2 01JUL21 0
2 01AUG21 0
3 O1FEB21 0
3 01MAR21 0
3 01APR21 0
3 01MAY21 0
3 01JUN21 0
3 01JUL21 1
我想要的输出
ID Date enrol enrol_flag
1 01JAN21 0 0
1 O1FEB21 1 1
1 01MAR21 1 1
1 01APR21 1 1
1 01MAY21 0 0
1 01JUN21 0 0
1 01JUL21 1 0
1 01AUG21 1 0
2 01JAN21 1 1
2 O1FEB21 1 1
2 01MAR21 1 1
2 01APR21 1 1
2 01MAY21 1 1
2 01JUN21 0 0
2 01JUL21 0 0
2 01AUG21 0 0
3 O1FEB21 0 0
3 01MAR21 0 0
3 01APR21 0 0
3 01MAY21 0 0
3 01JUN21 0 0
3 01JUL21 1 1
试试这个
data have;
input ID Date :date7. enrol;
format Date date7.;
datalines;
1 01JAN21 0
1 01FEB21 1
1 01MAR21 1
1 01APR21 1
1 01MAY21 0
1 01JUN21 0
1 01JUL21 1
1 01AUG21 1
2 01JAN21 1
2 01FEB21 1
2 01MAR21 1
2 01APR21 1
2 01MAY21 1
2 01JUN21 0
2 01JUL21 0
2 01AUG21 0
3 01FEB21 0
3 01MAR21 0
3 01APR21 0
3 01MAY21 0
3 01JUN21 0
3 01JUL21 1
;
data want;
set have;
by ID Date;
if first.ID then do;
enrol_flag = enrol;
d = 0;
end;
if enrol = 1 & d = 0 then do;
enrol_flag = 1;
d = 1;
end;
if enrol = 0 and d = 1 then enrol_flag = 0;
retain enrol_flag d;
run;
enrol
的序列与群id
可以形成0和1的带。 您希望在 enrol
从 1
转换到 0
后将每个点的标志设置为零,因此您需要一个辅助变量来跟踪该情况以执行 0 规则。
示例(DOW 循环):
data have;
input id date enrol;
attrib date informat=date7. format=date7.;
datalines;
1 01JAN21 0
1 01FEB21 1
1 01MAR21 1
1 01APR21 1
1 01MAY21 0
1 01JUN21 0
1 01JUL21 1
1 01AUG21 1
2 01JAN21 1
2 01FEB21 1
2 01MAR21 1
2 01APR21 1
2 01MAY21 1
2 01JUN21 0
2 01JUL21 0
2 01AUG21 1
3 01FEB21 0
3 01MAR21 0
3 01APR21 0
3 01MAY21 0
3 01JUN21 0
3 01JUL21 1
;
data want (keep=id date enrol flag);
do until (last.id);
set have;
by id;
_d = dif(enrol); /* unconditional place ensures consistent dif */
if first.id then flag=enrol;
else
if _d = -1 then _z = 1; /* track transition 1 -> 0 */
if _z
then flag = 0; /* enforce rule */
else flag = enrol;
output;
end;
run;