gen byte mage=.
sum lineno, meanonly
forvalues i = 1/`r(max)' {
gen byte tag = 1 if lineno==`i'
bysort hhid: egen byte iage = max(tag*age)
replace mage=iage if mlineno==`i'
drop tag iage
}
I tried changing -bysort hhid- to -by hhid- but the time needed for
the loop is the same. Running the loop -quietly- also makes no
difference. Can anything be done to make this loop go faster?
As other posters note, perhaps you don't even need a loop. But one
thing is worth remembering: in a large dataset, an if qualifier is
hideously slow compared to an in qualifier. That is, if you go through
the dataset once and figure out what the first and last record for each
family will be, an in-qualifier using those numbers will run _much_
faster than an if-qualifier, which must examine every case to see
whether it meets the conditions.