use observation sort observeid save observation, replace use household_head keep individid socialgpid hhd_sdate gen refdate = $refdate drop if refdate < hhd_sdate gen period = qofd(refdate )-qofd(hhd_sdate ) +1 expand period sort individid hhd_sdate by individid hhd_sdate: gen p= _n-1 gen quarterdate = qofd(hhd_sdate) + p gen refquarter = qofd(refdate ) sort individid quarterdate egen maxhhd_sdate = max(hhd_sdate), by(individid quarterdate) keep if hhd_sdate == maxhhd_sdate sort individid tostring quarterdate, generate(key) replace key = socialgpid + individid + key duplicates drop key, force sort key save crossehousehodlheadtemp, replace keep if refquarter == quarterdate format refdate %td sort individid duplicates drop individid, force save cross\crosshouseholdhead, replace