0
votes

I just learned how to use a for loop in Stata.

I tried this on my data in order to convert my string formatted variables to numeric ones and then move the new numeric variables right next to the old string formatted variables.

But somehow Stata gave me an error message:

foreach var of varlist city zipcode {
encode 'var', gen(_'var')
order _'var', after('var')
}

' invalid name
r(198);

I also tried the following:

foreach varlist in city zipcode {
encode 'varlist', gen(_'varlist')
order _'varlist', after('varlist')
}

invalid syntax 
r(198);

I guess these simple code snippets should work but I have no idea why they fail.

Could someone please help me out?

1

1 Answers

1
votes

You are using 'var' instead of `var' to refer to the local macro:

clear
set obs 5

generate city = string(runiform())
generate zipcode = string(runiform())

foreach var of varlist city zipcode {
    encode `var', gen(_`var')
    order _`var', after(`var')
}

list

     +-------------------------------------------+
     |     city      _city    zipcode   _zipcode |
     |-------------------------------------------|
  1. | .2047095   .2047095   .3913819   .3913819 |
  2. | .8927587   .8927587   .1196613   .1196613 |
  3. | .5844658   .5844658   .7542434   .7542434 |
  4. | .3697791   .3697791   .6950233   .6950233 |
  5. | .8506309   .8506309   .6866152   .6866152 |
     +-------------------------------------------+