Hello All,

I hope this message finds you well!

I have longitudinal unbalanced data and I am trying to identify in them the last assessment in each 6 months period since the first assessment. For example if one person had 5 assessments in the first 6 months I want to flag the 5th assessments in that first 6 months period.
I have been working for a while with the below code and something is not quite right with it and I am unable to discern the issue. Specifically, I am expecting the flags to be exclusif (i.e. what is flagged in the first 6 months cannot be flagged in the flag from 6 to 12 months, in the flag from 12 to 18 months, and in the flag from 18 months to 24 months) but unfortunately I keep getting multiple flags for the same screening number. Below is my code can someone identify an error?


Code:
local 6mos 183 //    DAYS IN 6 MONTHS
isid dbid screening_number, sort
//    CREATE STATA INTERNAL FORMAT NUMERIC DATE VARIABLE
by dbid (screening_number): assert date > date[_n-1] if _n > 1
by dbid (screening_number): gen delta = date - date[1]
by dbid (screening_number): egen flag6 = ///
    max(cond(delta <= `6mos', screening_number, .))
by dbid (screening_number): egen flag12 = ///
    max(cond(inrange(delta, `6mos'+1, 365), screening_number, .))
by dbid (screening_number): egen flag18 = ///
    max(cond(inrange(delta, `6mos'+2, 548), screening_number, .))
by dbid (screening_number): egen flag24 = ///
    max(cond(inrange(delta, `6mos'+3, 730), screening_number, .))
*****************************************************************

Best wishes,
Patrick