hi SAS community
i would like to have a code to calculate the values in "duration". THe dataset contains multiple patient MRI studies (Patient name). Each MRI study contains a variable number of sequences (e.g a,b,c for patient 1, whereas a,b,c,d for patient 3). Time start is the time that each sequence starts. Duration is what I would like to calculate: which is calculated by subtracting the time start from the line below (after sorting the dataset in this order). Obviously the data will have be to grouped by the MRI studies, so the last sequence of any given study does not have duration calculated (thus left blank) as we do not have the end time of the study. Many thanks for your help in advance.
Since SAS provides functions to look at previous record values I would sort and run things in reverse order then sort back.
proc sort data=have; by patientname descending time_start; run; data want; set have; duration=dif(time_start); by patientname; if first.patientname then duration=.; run; proc sort data=want; by patientname time_start; run;
The Dif function is difference of the current record from the previous. Using By processing so make sure that the first dif does not use the value from the previous patient.
Warning: Do you have any of these sequences that cross midnight? Your actual time, if time of day, may be an issue. Next, is if your times are using a 12 hour clock and not a 24 hour clock then crossing noon might an issue since you have not actually provided any values in that time range.
Since SAS provides functions to look at previous record values I would sort and run things in reverse order then sort back.
proc sort data=have; by patientname descending time_start; run; data want; set have; duration=dif(time_start); by patientname; if first.patientname then duration=.; run; proc sort data=want; by patientname time_start; run;
The Dif function is difference of the current record from the previous. Using By processing so make sure that the first dif does not use the value from the previous patient.
Warning: Do you have any of these sequences that cross midnight? Your actual time, if time of day, may be an issue. Next, is if your times are using a 12 hour clock and not a 24 hour clock then crossing noon might an issue since you have not actually provided any values in that time range.
hi ballardw,
the code works but the numbers generated for duration are negative (note that seriestimestamp is the time_start)
thanks
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.