I know that SAS can do this with PROC LIFETEST, but I want to attempt this by hand. Even though I can easily do this in Excel or R, this might be a good learning experience. I am essentially trying to reproduce the product-limit table for some survival data. Below is a look at how my data currently looks. The value in "AtRisk" is a macro variable placed in the dataset if it is the first observation.
What I want to do is calculate AtRisk(i) = AtRisk(i-1)-censored(i-1)-event(i-1). In other words, AtRisk for SurvivalTime=2 is 49-5-0=44. Then At Risk for SurvivalTime=2 is 44-0-1=43, etc.
I have tried using the RETAIN statement and the lag() function to perform this, but I cannot get either one to work. If you have any better ideas, please help me out!
Here is an example of my code that does not do the trick:
data data2;
set data1;
by _LABEL_; /* NOTE: _LABEL_ has the same value throughout the data */
if first._LABEL_ then atrisk=&atrisk.;
else atrisk=lag(atrisk);
run;
CURRENT DATA:
_NAME_ | SurvivalTime | Censorred | Event | AtRisk |
---|---|---|---|---|
COUNT | 1 | 5 | 0 | 49 |
COUNT | 2 | 0 | 1 | . |
COUNT | 3 | 0 | 1 | . |
COUNT | 4 | 1 | 0 | . |
COUNT | 5 | 0 | 1 | . |
... | ... | ... | ... | ... |
CORRECT DATA:
SurvivalTime | Censored | Event | AtRisk |
---|---|---|---|
1 | 5 | 0 | 49 |
2 | 0 | 1 | 44 |
3 | 0 | 1 | 43 |
4 | 1 | 0 | 42 |
5 | 0 | 1 | 41 |
... | ... | ... | ... |
%let AtRisk=49;
data want (drop=Last:);
input _NAME_ $ SurvivalTime Censorred Event;
retain AtRisk LastAtRisk;
AtRisk=ifn(_n_ eq 1,&AtRisk,
LastAtRisk);
LastAtRisk=AtRisk-Censorred-Event;
cards;
COUNT 1 5 0
COUNT 2 0 1
COUNT 3 0 1
COUNT 4 1 0
COUNT 5 0 1
;
How about this?
data data2;
set data1;
retain atrisk;
if _n_ = 1 then atrisk = &atrisk;
else atrisk = atrisk - censored - lag( event );
run;
%let AtRisk=49;
data want (drop=Last:);
input _NAME_ $ SurvivalTime Censorred Event;
retain AtRisk LastAtRisk;
AtRisk=ifn(_n_ eq 1,&AtRisk,
LastAtRisk);
LastAtRisk=AtRisk-Censorred-Event;
cards;
COUNT 1 5 0
COUNT 2 0 1
COUNT 3 0 1
COUNT 4 1 0
COUNT 5 0 1
;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.