First things first.
Do not (as in never) record dates as character variables. Even if you only have year and month (or year and quarter in your case), record them as two numeric variables. And if you also have day-of-month, then make a SAS date value (as I have done in creating variable END_OF_QUARTER in data set view NEED below by assuming last-day-of-month for every record):
dm 'clear log';
data have;
input Ric $3. Quarteryear :$6. ;
datalines;
JNJ 2010Q4
JNJ 2011Q1
IR 2011Q2
IR 2011Q3
IR 2011Q4
IR 2012Q1
IR 2012Q2
G 2002Q3
G 2002Q4
G 2003Q3
G 2003Q4
G 2004Q1
G 2004Q2
G 2004Q3
IRM 2004Q4
IRM 2005Q1
IRM 2005Q2
run;
data need (drop=_:)/view=need;
set have;
_year=input(quarteryear,4.);
_month=3*input(char(quarteryear,6),1.);
end_of_quarter=mdy(_month,1,_year);
end_of_quarter=intnx('month',end_of_quarter,0,'end');
format end_of_quarter date9. ;
run;
data want (drop=_:);
set need (keep=ric);
by ric notsorted;
merge need
need (firstobs=2 keep=end_of_quarter rename=(end_of_quarter=nxt_end_of_quarter));
_prev_gap_size=intck('qtr',lag(end_of_quarter),end_of_quarter)-1;
_next_gap_size=intck('qtr',end_of_quarter,nxt_end_of_quarter)-1;
new_appear = (first.ric=1) or (_prev_gap_size>=1);
spot_disappear = (last.ric=1) or (_nxt_gap_size>=1);
comeback = (first.ric=0) and (_prev_gap_size>=2);
run;
The real logic here is to use INTCK function to calculate the number of quarters from the LAGged and current values of END_OF_QUARTER - to record appearances or comebacks. And use the MERGE statement (notice the FIRSTOBS=2 parameter) to make available the value for the upcoming END_OF_QUARTER, to compare to the current value to identify upcoming gaps.
If INTCK generates a value of 1 (for a 1-quarter interval), then the gap is zero quarters.
... View more