Wednesday, November 12, 2014

Using Variables Names with Suffix or Prefix in a Loop with Stata [Data]

 

Putting the information here because I can never remember the damn syntax, and there's a pitfall if you use the wrong syntax.  Basically, you would want to use foreach with the "in" syntax. For example:

 

clear

set obs 1

gen AustraliaRecession = 1

gen AustraliaGDP = 1

gen CanadaRecession = 1

gen CanadaGDP = 1

gen GermanyRecession = 1

gen GermanyGDP = 1

l

foreach uCountry in Australia Canada Germany {

replace `uCountry'Recession = 0

replace `uCountry'GDP=2

 

}

l

 

The code above loops through the 2 sets of variables and replace the values. Note however, that foreach with the "of varlist" syntax might or might not work (and mostly likely not). Below is a situation where it will fail. You will get the error " Australia ambiguous abbreviation ".

 

clear

set obs 1

gen AustraliaRecession = 1

gen AustraliaGDP = 1

gen CanadaRecession = 1

gen CanadaGDP = 1

gen GermanyRecession = 1

gen GermanyGDP = 1

l

foreach uCountry of varlist Australia Canada Germany {

replace `uCountry'Recession = 0

replace `uCountry'GDP=2

 

}

l


The reason the code fails is because "of varlist" expects Australia to be a variable, and the standard behavior of Stata when you give a partial variable name is to assume the rest. However, in this case, Stata finds AustraliaRecession and AustraliaGDP -- thus it complains about the ambiguous abbreviation.