Help using Base SAS procedures

difference between consecutive dates

Reply
Occasional Contributor
Posts: 16

difference between consecutive dates

I have a lists of patients each with prescription dates. I would like to look at the prescription dates of each patient and see which patient has skipped medication say for 2months (60days). as an example, suppose patient A has prescription on the following dates, 01/Jan/2001, 01/Feb/2001,01/March/2001, 01/Jan/2002, 01/Feb/2002, 01/March/2002.

Because the number of days between the third and the fourth prescription is greater than 60 days, i would like the program to tell me that this patient has skipped medication. Am I making sense?? Can someone help.
Regular Contributor
Posts: 171

Re: difference between consecutive dates

You could sort by patient and date, use the lag function to calculate the number of days between successive prescription dates, and then select only those patients where the maximum number of days is greater than 60. For example:

[pre]
proc sort data=prescription_dates;
by patient date;
run;

data prescription_dates;
set prescription_dates;
by patient;
if first.patient then lastdate=.;
else lastdate = lag(date);
datediff = date-lastdate;
run;

proc sql;
select distinct patient, max(datediff) as number_of_days
from prescription_dates
group by patient
having number_of_days gt 60;
quit;
[/pre]
Valued Guide
Posts: 632

Re: difference between consecutive dates

A caveat if I may. Be careful when conditionally executing the LAG function. Very often the result is not quite what you expect. Try the following, which is very similar code:
[pre]proc sort data=sashelp.class out=class;
by sex age;
run;
data lagage;
set class;
by sex;
if first.sex then lastage=.;
else lastage = lag(age);
run;
proc print data=lagage;
var sex age lastage;
run;[/pre]
The problem is solved by executing the LAG function for every observation!!
In your code the two statements become:
[pre]
lastdate = lag(date);
if first.patient then lastdate=.;[/pre]
Super User
Posts: 9,682

Re: difference between consecutive dates

Yes.
Arthur Carpenter is right.
Be careful to use LAG(), It returns the current value when Lag() executes lastly.
And there is short way to use function DIF() which stands for date - lag(date).


Ksharp
N/A
Posts: 0

Re: difference between consecutive dates

You can also try next solution:

data final (drop=date_calc a b);
set test;
by id;

retain date_calc delete a;

if first.id then do;
a=_n_;
delete=0;
end;
else if delete ne 1 then delete=((date-date_calc)>=60);

date_calc=date;

if last.id and delete=1 then do;
b=_n_;
do i=a to b;
set test point=i;
output;
end;
end;
run;

Marius
Ask a Question
Discussion stats
  • 4 replies
  • 2093 views
  • 2 likes
  • 5 in conversation