Announcement

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

  • Conditioning on the iteration number within a loop

    Hi,

    I want to condition on the iteration number / iteration name within a loop. I'm currently doing it something like below (simplified code):

    Code:
    foreach i in A B C D E {
       ...
       replace x="something" if `i'=="A"
       replace x="something else" if `i'=="B"
    ​​​​​​​   replace x="something else" if `i'=="C"
    ​​​​​​​   replace x="something else" if `i'=="D"
    ​​​​​​​   replace x="something else" if `i'=="E"​​​​​​
       ...
    }
    But it's showing me errors.

    What's the correct way of doing it? Thanks!

  • #2
    Code:
    replace x="something" if "`i'"=="A"
    Without the quotation marks, you are comparing A=="A", and Stata will interpret A as the name of a variable (or an abbreviation for the name of a variable) rather than as the iteration name.

    Comment


    • #3
      This simplified code isn't really useful. It's clear that this doesn't make sense:

      Code:
       
        replace x="something" if `i'=="A"
      Because if `i'=="A" should say something about whether or any given observation should be replaced or not. It should, therefore, evaluate to true for some observations and false for others. The code you have here doesn't achieve this.

      The problem is that it's not clear what you are trying to accomplish, so it's not clear what you should do instead. A data example generated with -dataex- and a clear description of the desired behavior would be very useful here. Also, when you get an error, you should post the exact error. You have 62 posts here, so you're not exactly new to the forum. It's time to learn how to ask a question in a way that is informative enough to get a decent answer.

      Comment


      • #4
        Originally posted by William Lisowski View Post
        Code:
        replace x="something" if "`i'"=="A"
        Without the quotation marks, you are comparing A=="A", and Stata will interpret A as the name of a variable (or an abbreviation for the name of a variable) rather than as the iteration name.
        Thanks so much. This fixed the problem.

        Comment

        Working...
        X