I am trying to select 10 controls per case (using risk-set sampling) matched by general practice. I used a loop for that as shown below, but I need another loop within to ensure that all controls fulfil eligibility criteria. So, after running the sttocc command, I am struggling to find the syntaxes for fitting in another loop to REMOVE all non-eligible controls while repeating the iterations UNTIL 10 controls are selected per case. The eligibility criteria include age at index date should not be less than 15 years and the transfer out of practice should not be before the index date.


These are the commands I have so far:

set more off
use cohort, clear
set seed 404507 //a random number, to keep for replication

forval i=1/777 { // 777 is a maximum practice id,
use cohort, clear
keep if pracid==`i'
qui tab suicide
if r(r)==2 {
sttocc, n(10) /* NB- i have inserted a loop here as I will demonstrate below */
save temp/matched`i' //, replace
}
}

use temp/matched1, clear
forval i=2/777 {
capture append using temp/matched`i'
save matched, replace
}
I tried to fit in this loop to rule out noneligible controls and to keep the loop going until there are 10 controls per case, but I keep getting "variable clusters already defined". I tried many other ways around that but non seem to be working. I would truly appreciate your help.

forval d=1/11 { /*I am trying to tell stata to repeat the iterations 11 times to get a total of 1 case + 10 controls= 11 */
by _set: generate clusters= _n /*trying to get the total number of cases and controls in each set*/
keep if clusters== `d'
format index dobirth transferoutdate %d
keep if (index- dobirth) >= 5475 /*age in days */
keep if transferoutdate > index



}