hey buddy,
not the tidiest code but I think this does what you want:
data input;
input USERID $1 Year Month Flag 4.;
datalines;
A 2021 12 0
A 2022 1 1
A 2022 2 1
A 2022 3 0
A 2022 4 0
A 2022 5 0
B 2021 8 0
B 2022 9 1
B 2022 10 1
B 2021 11 0
B 2021 12 0
B 2022 1 0
;
run;
data step1;
retain flag date_cat months_since_last_event;
set input;
by userID ;
prev_flag =lag(flag);
if first.userID then do;
months_since_last_event = .;
end;
else if flag =0 and prev_flag =1 then do;
months_since_last_event=1;
end;
else if flag =1 then do;
months_since_last_event=0;
end;
else do;
months_since_last_event+1;
end;
drop prev_flag;
run;