/***************************************************************************************************************** SAS file name: consecutive_dates_observations.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to work with consecutive observations and dates in SAS Author: Peter Clemmensen Creation Date: 15/10/2019 This program supports the blog post "Consecutive Observations and Dates in SAS" on SASnrd.com *****************************************************************************************************************/ /* Test data set */ data have; input id $ event; datalines; 1 50 1 20 1 20 1 20 1 30 2 40 2 40 2 30 2 30 3 30 3 30 3 40 3 40 3 40 3 40 3 10 ; /* Flag consequitive events occuring at least 3 times within the same by-group */ data want; do _N_=1 by 1 until (last.event | last.id); set have; by id event notsorted; flag=ifn(_N_ ge 3, 1, 0); end; do _N_=1 to _N_; set have; output; end; run; /* Test data set */ data have; input id $ value $; datalines; 1 high 1 medium 1 high 2 medium 2 high 2 high 2 high 2 medium 2 medium 2 low 3 high 3 high 3 medium 3 medium 3 low 3 low 4 low 4 high 4 high 4 high 4 high 5 medium 5 medium 5 medium 5 low 5 low 5 medium 5 medium 5 low 6 low 6 high 6 high 6 high 6 medium 6 medium 7 medium 7 medium 7 high 7 high 7 high 7 high 7 high 7 high 7 high ; /* Use a hash object to find the last 2 occuring ids with more than 3 consecutive 'high' events */ data want(drop=rc); if _N_=1 then do; declare hash h(ordered: 'A'); h.definekey('_N_'); h.definedata('_N_', 'id', 'value', 'c'); h.definedone(); declare hiter hi ('h'); end; do until (last.id | last.value); set have end=lr; by id value notsorted; c=sum(c, 1); end; if value='high' & c ge 3 then h.add(); if lr; do _iorc_=1 to 3 while (hi.last()=0); output; rc=hi.next(); h.remove(); end; run;