/***************************************************************************************************************** SAS file name: consecutive_dates.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to handle consecutive dates or years in SAS Author: Peter Clemmensen Creation Date: 16/11/2019 This program supports the blog post "Working With Consecutive Dates and Years in SAS" on SASnrd.com *****************************************************************************************************************/ /* Example data */ data have; input id date :ddmmyy10.; format date ddmmyy10.; datalines; 1 20/11/2019 1 21/11/2019 1 22/11/2019 1 25/11/2019 1 27/11/2019 1 29/11/2019 2 20/11/2019 2 21/11/2019 2 23/11/2019 2 25/11/2019 2 26/11/2019 2 28/11/2019 3 29/11/2019 3 01/12/2019 ; data want(drop=_:); set have; by id; merge have have (firstobs=2 rename=(id=_id date=_date)); _dtdif=dif(date); flag=0; if date+1=_date & last.id=0 then flag=1; if _dtdif=1 & first.id=0 then flag=1; run; /* Example data */ data have; input id year; datalines; 1 2003 1 2004 1 2005 1 2006 1 2008 1 2009 2 2006 2 2003 2 2004 2 2009 2 2005 2 2008 3 2003 3 2004 ; /* Flag observation if the year is part of a 4 year consecutive streak like 2003, 2004, 2005, 2006. Not necessarily in sorted order in the data. As long as it is there within the same gruop, flag is set to 1 */ data want(drop=y c); if _N_=1 then do; declare hash h(dataset:'have'); h.definekey('id', 'year'); h.definedone(); end; set have; do y=-3 to 3; if h.check(key:id, key:year+y)=0 then c=sum(c, 1); else c=0; if c=4 then do; flag=1; leave; end; end; run;