Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • r(198) error with a foreach loop

    Dear Statalist community,

    I have the following code that I am running on foreach:

    Code:
    foreach y in trade tariff_s tariff_w freedom {
    
    foreach x in suffrage_dummy1 suffrage_dummy2 suffrage_dummy3 suffrage_dummy4 suffrage_dummy5 suffrage_dummy6 suffrage_dummy7 suffrage_dummy8 suffrage_dummy9 {
    
    areg `y' `x', a(country)
    outreg2 using regression_table`y'_`x'.doc  
    
    areg `y' L3.'x' L2.'x' L1.'x' 'x' F1.'x' F2.'x' F3.'x', a(country)
    outreg2 using regression_table`y'_`x'.doc
    
    }
    }
    After executing, Stata is showing me the error (198) ' invalid name. I can't workout where the problem is.

    Thanks.

    Ashvinder

  • #2
    The problem is coming from all those 'x'-s in the second -areg- command. You are trying to dereference local macro x (which is controlled by the foreach x loop). But the proper syntax for that is:

    Code:
    `x'
    not
    Code:
    'x'
    The character you need is located, on a US English keybaord, in the upper left hand corner of the layout, on the key just to the left of the 1! key. I think you actually know this, as you did it correctly in the first -areg- command, both -outreg2- commands, and even for `y' in the second -areg- command.

    General tip in debugging problems inside loops: Stata does not echo the commands to the output when it runs a loop. So it is not always clear which command inside a loop is throwing the error message. You can reveal that by putting
    Code:
    set tracedepth 1
    set trace on
    just at the top of the loop. This will cause Stata to display the commands as the loop executes and iterates. Even better, when there are commands that refer to local or global macros, Stata will show you what the command looks like after the macros are expanded. Had you used this trick, you would have seen that the second -areg- was coming out as -areg trade L3.'x' L2.'x'...- with no mention at all of suffrage_dummy1. You might not have immediately recognized that the left quote was the source of the problem, but you would certainly have focused your thoughts on "what's wrong with that macro x!"
    Last edited by Clyde Schechter; 27 Jul 2017, 14:12.

    Comment


    • #3
      Thank you Clyde, the code works now.

      Comment

      Working...
      X