Using a loop to select countries in a panel

Sometimes, you need to extract some countries when you are using a panel. The most simple way to proceed is to use a loop after the creation of a dummy variable:

// Loop to select countries
gen tokeep = 0

foreach v in AUS BRA CAN CHL COL CZE EUR HUN IND ISR JPN ///
KOR MEX NOR NZL PHL POL ROU SGP ZAF SWE CHE THA GBR USA {
replace tokeep = 1 if iso3c == "`v'"  	
}

drop if tokeep!=1

Be careful to use "`v'" if the identifiers for the country codes AUS BRA CAN CHL COL CZE EUR HUN IND ISR JPN KOR MEX NOR NZL PHL POL ROU SGP ZAF SWE CHE THA GBR USA are stored in strings. In this case, the country identifiers iso3c are stored as strings.

I express my gratitude to Nick Cox and others for providing such inspiring responses to this ‘Stack Overflow’ question: https://stackoverflow.com/questions/37475162/foreach-for-string-values-manual-list.

I hope you will find it useful!