Announcement

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

  • Stata ignores else condition in if-else blocks within forval loop

    Hey everyone,

    I have three files named something like File_1, File_2, File_3, which I am importing and cleaning in a forval i = 1(1)3 {} loop.

    File 1 and 3 have a slightly different structure than File 2, so I have included the following if-else statements in the loop to deal with this. The code looks something like this:

    forval i = 1(1)3 {
    import File_`i', clear
    processing common to all files (i.e operations on variables found in all three files)


    if `i' == 2 {
    separate processing for file 2
    (i.e operations on variables only in file 2)
    }

    else {
    processing for files 1 and 3
    (i.e operations on variables not in file 2)
    }

    save File_`i'_clean, replace
    }

    The first bloc works just fine, but Stata decides to execute the second block regardless of the value of `i'. I'm at my wits end trying to figure out why this could be the cause. Could there be any reason?

    I have tried replacing the second block with:
    else if `i' == 1 | `i' == 3
    if `i' == 1 | `i' == 3
    if inlist(`i', 1, 3)

    None of these work. Stata just keeps ignoring the logical.

    Any help would be appreciated. Unfortunately, I cannot share a concrete example the data since it contains PID. But, errors result from the second block being evaluated for file 2 which does not have those variables.

  • #2
    I can't see anything in what you have posted that would cause the problem you describe, which leads me to believe that there is something in your actual code that is different. If you could post the exact code (not the data), pasted literally from your results window, that might help with a diagnosis.

    You didn't mention what you might have tried to diagnose the problem yourself. In your situation I would insert various display statements to see what is going on. I'm thinking of something whose structure in outline form would look this (which you may already have tried):

    Code:
    forval i = 1(1)3 {
       di "i = `i', processing for all files"
      < your actual code>
       if `i' == 2 {
          di "handling i = 2"
        <your code>
       }
       else {
          di "handling i != 1 or 3"
       <your code>
       }
       di "Saving file `i'  "
       di "-------end for `i'" _newline
    }
    You could get much the same information with -set trace on-, but I often like this old-fashioned approach.

    Comment


    • #3
      Actually, you're correct. I used the debugging tip and found out that 1) the loop worked correctly, and 2) I had incorrectly referenced one of the filetypes in the second statement via a small typo. Thanks anyway and apologies for any inconvenience.
      Last edited by Adithya Raajkumar; 28 Nov 2020, 13:19.

      Comment

      Working...
      X