use ${temploc}junk,clear mac def sort="$family `*'" /* sorts data in ram by $sort & within by group defined by $sort, counts the number of year 1 & year 2 observations. $y1 is the count of year 1 observations & $y2 is the year 2 count. */ sort $sort year mac def y1 : tempvar mac def y2 : tempvar qui by $sort : gen byte $y1=year==$yr1 qui by $sort : replace $y1=sum($y1) qui by $sort : replace $y1=$y1[_N] qui by $sort : gen byte $y2=year==$yr2 qui by $sort : replace $y2=sum($y2) qui by $sort : replace $y2=$y2[_N] save ${temploc}junk,replace keep if $y1==1 & $y2==1 if _N>0 { drop $y1 $y2 replace match_id=year==$yr1 replace match_id=sum(match_id) replace match_id=match_id + $leftoff mac def leftoff=match_id[_N] replace level=$step*2 - 1 if $step==1 { save ${temploc}matched,replace } else { save ${temploc}_temp,replace use ${temploc}matched append using ${temploc}_temp save ${temploc}matched,replace } } use ${temploc}junk,clear drop if $y1==1 & $y2==1 save ${temploc}junk,replace exit 0