0

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?

Todd
  • 399
  • 3
  • 18

1 Answers1

1

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 |
     +-------------------------------------------+
  • @Hi, Yes. you're right. It worked! Many thanks to you. – Todd Jul 29 '18 at 02:29
  • Can I ask one more question? I referenced a video on youtube, textbooks, and materials on the internet but they never told me about this (maybe they considered this as a default prior knowledge?). So my question is do I have to always use `something' rather than 'something' when using for loop in Stata? – Todd Jul 29 '18 at 02:33
  • is there any case that I use just regular single quotes, ' ',? – Todd Jul 29 '18 at 02:33
  • 1
    You always have to call local macros using ` ' and not ' '. This is true irrespective of whether you are in a `for` loop or not. I would strongly recommend you to read the [official chapter](https://www.stata.com/manuals/pmacro.pdf#pmacroRemarksandexamplesFormaldefinitionofamacro) on Stata's macros. –  Jul 29 '18 at 07:24
  • 1
    Uncompromising advice: Stata's manuals are the only serious documentation if you are serious about Stata programming. You can waste an enormous amount of time just Googling or watching videos. – Nick Cox Jul 29 '18 at 08:17
  • 1
    Paired upright single quotes can be used within literal strings. But they never have syntactic meaning. The reason is that they can't be nested unambiguously. – Nick Cox Jul 29 '18 at 08:19