stata - Defining groups within an interval -
in stata following data
id date 1 1/1/2010 2 1/1/2010 3 1/4/2010 4 1/5/2010 5 1/8/2010 6 1/10/2010 7 1/11/2010 i trying create variable dummyi gives unique variable of ids occurred within 3 days (before or after) of focal id.
i first wanted identify ids within 3 day window of given id , assign unique number of those.
qui forvalues = 1/`=_n' { gen dummy`i' replace dummy`i' = `i' if date <= (date[`i']-3) & id == `i' } this approach getting there there missing id values, not neatly sequential , wasn't taking ids occurred before account. finally, multiple ids fall 2 groups (e.g. id==5) , not sure how separate without creating separate dummy variables, fine.
resulting data should following.
id date dummy1 dummy2 dummy3 dummy4 dummy5 dummy6 dummy7 1 1/1/2010 1 1 1 0 0 0 0 2 1/1/2010 1 1 1 0 0 0 0 3 1/4/2010 1 1 1 1 0 0 0 4 1/5/2010 0 0 1 1 1 0 0 5 1/8/2010 0 0 0 1 1 1 1 6 1/10/2010 0 0 0 0 1 1 1 7 1/11/2010 0 0 0 0 1 1 1
clear set more off *----- example data ----- input /// id str10 date 1 "1/1/2010" 2 "1/1/2010" 3 "1/4/2010" 4 "1/5/2010" 5 "1/8/2010" 6 "1/10/2010" 7 "1/11/2010" end gen date2 = date(date, "mdy") format %td date2 drop date list *----- want ----- isid id levelsof id, local(levid) forvalues = 1/`=_n' { local lid : word `i' of `levid' gen ind`lid' = inrange(date2[`i'], date2 - 3, date2 + 3) } list, sep(0) levelsof used in case id irregular sequence. indicator variable (you call dummy) named according corresponding id.
see help extended_fcn if don't have experience extended macro functions (local lid : word ...).
Comments
Post a Comment