Announcement

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

  • Using global variables within forvalue loops

    I am trying to design a for loop that can be easily adapted for the input values but cannot work out a way to use global variables within my for loop. I have developed a very simple example to help isolate the problem. Essentially, this is the basic code:


    Code:
    clear all
    
    sysuse auto.dta
    
    gen tax = 0
    
        forvalues y = 0(1)10 {
        replace tax = `y'
        // other code...
        }
    And now i want to make it more flexible by changing the lower, sensitivity and upper bounds of the forvalues loop:

    Code:
    sysuse auto.dta
    
    gen tax = 0
    
    global low = 0
    global sensitivity = 1
    global high = 10
    
        forvalues y = ${low}(${sensitivity})${high} {
        replace tax = `y'
        }
    However, when i run this i get an error saying:
    program error: code follows on the same line as open brace
    Why am I getting this error and how do i fix it?

  • #2
    No need for the curly brackets when calling the global macro. See p5 here for examples: https://www.stata.com/manuals13/pmacro.pdf
    Code:
    forvalues y = $low ($sensitivity) $high {
        replace tax = `y'
    }

    Comment


    • #3
      Jorrit addresses how to fix the problem. I'd add that the problem itself is not due to an obvious error in the code for the forvalues loop, but rather is due to a shortcoming in Stata's parsing and documentation.

      Stata apparently scans the forvalues command for the required trailing open brace before doing substitution for macros, and it finds the open brace surrounding your first global macro name, and thinks it has found what should be the end of the command.

      Nothing I have found in the documentation suggests it is ever an error to use ${x} where $x is allowed, so I think you have stumbled across an "undocumented feature" of Stata.

      It seems to me that in scanning for the trailing open brace, Stata would be better off scanning from right to left, looking for the final nonblank character on the line, rather than left to right looking for an open brace. But perhaps I overlook something.

      Comment


      • #4
        Another dimension -- of practice rather than principle -- is that (speculation!) this bug hasn't surfaced before (much, if at all) because most Stata programmers would see no point to using globals for this purpose. At most they would use local macros.

        Comment

        Working...
        X