Announcement

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

  • Trouble with if statement in loop

    Eventually, I would like to loop over about 5 years of data. Variable names differ by year, so I'm trying to make my "keep" statement conditional on the file being from a certain year. Here's a simplified version of my code:

    Code:
    foreach yr in 2000 {
        import excel "S:\Stations\tracts_`yr'.xls", firstrow clear
        keep GEOID Shape_Area if `yr'>2009
    }
    I'm getting the error: "variable GEOID not found". However, I don't want it to try to execute the keep statement if the year is not 2010 or beyond.

    Thanks!

  • #2
    Your statement -keep GEOID Shape_Area if `yr' > 2009- does not do what you think it does. YOu have used the -if- qualifier here. So what that statement means is that the statement is always executed, regardless of the value of yr. The execution of the statement causes Stata to try to keep the variables GEOID Shape_Area in those observations in the data set that satisfy the condition `yr' > 2009. But if the data set has no variable named GEOID, then Stata never even gets to looking at whether `yr' > 2009. What you need instead is the -if- command.

    Code:
    foreach yr in 2000 { 
        import excel "S:\Stations\tracts_`yr'.xls", firstrow clear
        if `yr' > 2009 {
             keep GEOID Shape_Area
        }
    }
    That said, your code makes no sense in any case. There is no reason to have a loop if you only want to execute it for yr = 2000. And the test of whether `yr' > 2009 is also superfluous if the only value of yr is 2000.

    Comment


    • #3
      The distinction between the if qualifier and if command is really helpful.

      Yes, I recognize that the code currently doesn't make any sense. It originally was more complex, but I simplified it to try to find the error. Now that I know what I've been doing wrong, I'll add the other years to the loop and the additional statements.

      Thanks!

      Comment

      Working...
      X