datesas

Trying to calculate time between subsequent appointments in SAS


I am working with a dataset that has multiple visit dates per ID. I am trying to calculate the time between each subsequent appointment (visit 1 vs visit 2, visit 2 vs visit 3, etc.).

My data currently looks like this

data test;
input ID visit_dt :mmddyy10.;
format visit_dt mmddyy10.;
datalines;
1 06-14-2021
1 10-18-2021
1 12-16-2021
1 01-29-2022
2 07-17-2021
2 11-22-2021
2 12-23-2021
2 02-06-2022
;
run;

I am looking for the creating of a variable that tells the number of days between visits (ex: the second observation of the above data would have 126 days between June 14 and October 18th listed in the variable)

Any help with this would be much appreciated!! thank you in advance


Solution

  • Use a BY <var> statement, automatic variable FIRST.<var> and DIF function.

    Example:

    The DIF function computes the difference between the current value of a variable and the prior value of the variable.

    data want ;
      set have ;
      by id ;
      daysSincePrior = DIF(visit_dt) ;
      if first.id then daysSincePrior = .; 
    run ;