Hi there,
I am trying to calculate the difference in dates among records with the same ID. I would like the derived variable to look similar to the one below.
ID Date DateDiff (derived new variable)
1 01JAN21 9
1 10JAN21 9
2 05FEB22 0
2 05FEB22 0
Any help is much appreciated, thank you!
Do you always have two observations per id, or can there be more? If there can be more, which difference should be taken?
One way:
proc sql;
create table want as
select
id,
date,
max(date) - min(date) as datediff
from have
group by id
;
quit;
Given data like this
data have;
format id 8. date date9.;
informat date date.;
input id date;
cards;
1 01jan21
1 10jan21
2 5feb21
2 5feb21
;run;
you can use code like this
data want;
set have;
by id;
datediff=dif(date);
if first.id the datediff=.;
run;
The code will work if your dates are SAS date values, as shown in the example.
- although I am not quite sure why your example data show the difference to the next record for the first record in each group.
If that is really what you want, it can be done like this:
data want;
set want;
by id;
if first.id and not last.id then do;
_N_=_N_+1;
set want(keep=datediff) point=_N_;
end;
run;
Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.
Register today!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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: