I am dropping observations based on the if statement (drop if entryyear~=entryyear_surv) written in a do file. I have all the code in the do file highlighted and run it. I've run the code several times, and I got same results for the 1st stage but from 2nd stage different results are obtained. No code has changed between each time I run it, and 'sort' and 'sort,table' doesn't work. Below is the part of my do file. Thanks for your help in advance.



use admin_18, clear
merge m:m birthdate sex country immvisa_raw using 2018f_1

keep if _merge == 3

/*1st stage*/
sort birthdate sex country immvisa_raw, stable
egen matchid = group(birthdate sex country immvisa_raw)
drop if matchid == .
duplicates tag matchid, g(dup)


/*2nd stage*/
by pid, sort: drop if (entryyear~=entryyear_surv) & dup>0