BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

Hello, 

 

I am trying to use a date variable to calculate the difference between two dates. I am trying to see the difference between the first and last observation for a given ID, but sometimes there are more than 2 observations per individual. Take the sample data below:

 

ID                DateStamp

1                 01AUG2020

1                 07SEP2020

2                 01AUG2020

2                 08AUG2020

2                 11SEP2020

3                 05JUN2020

3                 01AUG2020

 

I want to end up with a variable that is the date difference between the first ID entry and the last ID entry (for example, for ID #1, the date variable would be the difference between September 7 and August 1, for ID #2, the date variable would be the difference between August 1 and September 11, etc). 

 

Can someone help me with this? 

 

Thank you!

2 REPLIES 2
novinosrin
Tourmaline | Level 20
data have;
input ID                DateStamp :date9.;
format datestamp date9.;
cards;
1                 01AUG2020

1                 07SEP2020

2                 01AUG2020

2                 08AUG2020

2                 11SEP2020

3                 05JUN2020

3                 01AUG2020
;

proc sql;
 create table want as
 select id, range(datestamp) as datediff
 from have
 group by id;
quit;

/*Or*/

proc summary data=have nway;
 class id;
 var datestamp;
 output out=want range=Datediff;
 format datestamp;
run;
Cynthia_sas
Diamond | Level 26

Hi:

  And, in the interest of completeness.... if all you need is a report of the difference, you can get that directly from the original data (HAVE) without creating a second table using either PROC REPORT or PROC TABULATE:

Cynthia_sas_0-1600524494293.png

Using this code:


proc report data=have;
  title 'proc report solution';
  column id datestamp,range;
  define id / group;
  define datestamp/analysis ;
  define range / 'Difference' f=6.0;
run;

proc tabulate data=have f=6.0;
  title 'proc tabulate solution';
  class id;
  var datestamp;
  table id=' ',
        datestamp*range='Difference'/Box=ID;
run;
title;

Hope this helps,

Cynthia