use houseres sort socialgpid egen counter = count(episodeid), by(socialgpid) drop if (res_edate != . & res_edate < $refdate ) drop if (res_sdate != . & res_sdate > $refdate ) gen refdate = $refdate keep socialgpid locationid sort socialgpid duplicates drop socialgpid, force sort socialgpid save cross\crosshouseresidency, replace