Solved
New Contributor
Posts: 2

retain variable across observations

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.

Accepted Solutions
Solution
‎01-12-2012 10:45 AM
Super Contributor
Posts: 1,636

Re: retain variable across observations

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

All Replies
Solution
‎01-12-2012 10:45 AM
Super Contributor
Posts: 1,636

Re: retain variable across observations

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

Occasional Contributor
Posts: 6

retain variable across observations

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;

New Contributor
Posts: 2

retain variable across observations

Thank you.

🔒 This topic is solved and locked.