introductory text
final text
Code:
capture: drop *_days // dropping the wrong _days-variables ;-) unab daycountvars : schoolclose* // use local for looping over schoolclose-variables foreach daycountvar of local daycountvars { bysort regionname `daycountvar' (date): gen `daycountvar'_days = _n if `daycountvar'==1 // gen number within group only for cases where schoolclose-variable equals 1 bysort regionname (date): replace `daycountvar'_day = `daycountvar'_day[_n-1] if missing(`daycountvar'_days) & !missing(`daycountvar'_days[_n-1]) // replace by value of the previous observation within group when not missing order `daycountvar'_day, after(`daycountvar') // oder new variable after original one }