/* 以下部分计算censor,time2event*/
/* 1、计算censor的值*/
/* (1) 1-min(status,lstatus):当本条obs与上条obs status的值不同时,值为1,相同时为0*/
/* (2) max(first.id,censor):by组开始时,强制值为1,其他时候取上条obs的censor的值*/
/* (3) min(a,b):因为取min,必须a,b两部分同时为1的时候才为1,通过censor的滞后判断event的结束或延续*/
censor=min(1-min(status,lstatus),max(first.id,censor));
/* 2、计算time2event的值*/
/* (1) 条件部分:*/
/* a (1-censor) and (1-Time2Event):censor=0(event发生) and time2event=0(first event)的时候*/
/* b last.id and censor:by组末尾 and censor=1(event未发生)的时候*/
/* (2) 计算部分:*/
/* a 判断 last.id and censor:(event未发生)保持day的值,否则置0*/
/* b max(lday,day):取最大值*/
if (1-censor) and (1-Time2Event) or last.id and censor then
Time2Event =max(lday,(last.id and censor)*day );
/* 在每个by组的末尾output*/
if last.id then output;
/* 计算部分结束,设置滞后值开始*/
/* 以下部分获取滞后值,在by组结尾重置变量为初值*/
/* 1、仅在每个by组的末尾,重置Time2Event的值为0*/
time2Event=time2Event*(1-last.id);
/* 2、当疑似event开始时,将当前观测day的值赋给lday*/
if status=1 and lstatus=0 then lday=day;
/* 3、将当前观测status的值赋给lstatus,仅在每个by组的末尾,重置lstatus的值为0*/
lstatus=status*(1-last.id);
data had2(drop=day status flag status1);
set had;
retain flag;
by id day;
time2event=lag(day);
status1=lag(status);
if first.id then do;
status1=.;
flag=0;
end;
if status1=1 and status=1 then do;
censored=0;
output;
flag=1;
end;
if last.id and flag=0 then do;
time2event=day;
censored=1;
output;
end;
run;