Hello. I want to retain a variable value across multiple observations in order to do comparisons.
ID Date1 Date2
1 20100101 20100201
1 20100110
1 20100115
1 20100215
2 20100115 20100215
2 20100130
2 20100201
...
I want to create a new variable with value=1 if Date1<=Date2 and value=0 if Date1>Date2 for each ID.
I think it requires "retain" but I cannot find the solution.
data have;
infile cards missover ;
informat date1 date2 yymmdd8.;
format date1 date2 mmddyy10.;
input id date1 date2 ;
cards;
1 20100101 20100201
1 20100110
1 20100115
1 20100215
2 20100115 20100215
2 20100130
2 20100201
;
data want (drop=hold_date2);
set have;
retain hold_date2;
if date2 ne . then hold_date2=date2;
else date2=hold_date2;
if date1 le date2 then value=1;
else value=0;
proc print;run;
Linlin
data have;
infile cards missover ;
informat date1 date2 yymmdd8.;
format date1 date2 mmddyy10.;
input id date1 date2 ;
cards;
1 20100101 20100201
1 20100110
1 20100115
1 20100215
2 20100115 20100215
2 20100130
2 20100201
;
data want (drop=hold_date2);
set have;
retain hold_date2;
if date2 ne . then hold_date2=date2;
else date2=hold_date2;
if date1 le date2 then value=1;
else value=0;
proc print;run;
Linlin
Slightly different from Linlin's approach:
1) does not populate the missing value of date2:
data want (drop=_:);
set have;
retain _d2;
_d2=coalesce(date2,_d2);
value=ifn(date1<= _d2,1,0);
run;
2)does populate the missing value:
data want (drop=_:);
set have ( keep=date2 obs=0) have (rename=date2=_d2);
date2=ifn(_d2 ne ., _d2,date2);
value=ifn(date1<= date2,1,0);
run;
Thank you.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.