Announcement

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

  • forvalues with local variables

    I have the following problem with Stata 13.1: I am trying to run a loop with varying start and end points (determined by a numerical "year" variable), which will depend on fipscode. I would like to run the loop from the second-earliest year to the last year.

    I run:
    Code:
    quietly summarize year if fipscode == 17019
    
    local min1 `r(min)'
    local max1 `r(max)'
    
    local startyear `min1'+1
    
    
    forvalues y = `startyear'/`max1' {
    
    *** do something ***
    
    }
    Stata returns r(198) syntax error. (The syntax error is not related to the contents of ** do something **.) The
    Code:
     forvalues
    command does work if I instead do:

    Code:
    forvalues y = `min1'/`max1' {
    
    *** do something ***
    
    }
    My problem must come because
    Code:
    local startyear `min1' + 1
    is not behaving as I think it is, but I don't know what my mistake is. If, for example, `min1' above is 1993, then when I do

    Code:
    di `startyear'
    I see 1994, as expected. To add to my confusion, though, if I do
    Code:
    di `startyear'*5
    I get 1998, while
    Code:
    di 5*`startyear'
    returns 9966. Neither is the right answer and I don't know why the answers are different! Thank you in advance for correcting my misunderstanding.

  • #2
    local startyear `min1'+1
    is the source of your problem.

    When you get down to
    Code:
    forvalues y = `startyear'/`max1'
    Stata expands `startyear' to `min1'+1, which then further expands to something like 2005+1 (if, for example, the smallest value of year was 2005). So now Stata is confronted with:

    Code:
    forvalues y = 2005+1/2015 // ASSUMING MAX1 CONTAINS THE VALUE 2015, AS AN EXAMPLE
    The problem with that is that 2005+1 is an expression, but -forvalues- requires a number.

    You can solve this by defining the local macro startyear a little differently:

    Code:
    local startyear = `min1'+1
    The use of the equals sign tells Stata not to copy `min1'+1 as a string but to actually evaluate the expression `min1'+1 and store the result in local macro startyear. When you do that, the macro expansion will get you to
    Code:
    forvalues y = 2006/2015 // OR WHATEVER THE NUMBERS ARE
    and you should have smother sailing.

    Comment


    • #3
      That does fix the problem. I didn't try an '=' sign there. Thanks!

      Comment

      Working...
      X