You may want more than a flag variable. Here is code to count the number of earlier admission dates within 2 years (nprior), and the number of later admission dates within two years (nafter):
data counts (drop=_:);
set have (in=firstpass) have (in=secondpass);
by patient_id;
array dates{0:50} _temporary_;
if first.patient_id then call missing(of dates{*},_n1,_n2);
_n1+firstpass;
if firstpass then dates{_n1}=admit_dt;
if secondpass;
_n2+1;
_cutoff=intnx('year',admit_dt,-2,'s');
do nprior=0 by 1 until (dates{_n2-1-nprior}<_cutoff);
end;
_cutoff=intnx('year',admit_dt,+2,'s');
do nafter=0 by 1 until (dates{_n2+1+nafter}>_cutoff);
if dates{_n2+1+nafter}=. then leave;
end;
run;
This assumes data are sorted by admit_dt within patient_id. Also make sure that the lower bound of the DATES array is zero, and the upper bound is at least 1 more than the maximum number of single-patient admissions in dataset HAVE.
... View more