Announcement

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

  • Combining AND + OR Statements

    Hi all,

    Quick question I am tripping up on: if I use this syntax
    Code:
    replace XXX = XXX if var1 < 100 & var2 == 2000 | var3 == 3000
    Does this do the replacement based on the var1 AND the var2 OR the var3 statement? i.e., I want the var1 to be true for it to replace, and then I want either the var2 OR the var3 to be true to replace.

    I believe that if I reordered to this, it does not work as intended. I.e., it doesn't group var2/3 together. I think it instead needs either var2==2000 and then var3==3000 AND var1<100 to be true.
    Code:
    replace XXX = XXX if var2 == 2000 | var3 == 3000 & var1 < 100

  • #2
    Edit: I think it will only work as intended if I use parentheses:
    Code:
    replace XXX = XXX if var1 < 100 & (var2 == 2000 | var3 == 3000)

    Comment


    • #3
      Here's the paragraph that explains everything:

      13.2.5 Order of evaluation, all operators

      The order of evaluation (from first to last) of all operators is ! (or ~), ^, - (negation), /, *, - (subtraction), +, != (or ~=), >, <, <=, >=, ==, &, and |.
      That said, I would fail a test based on whether I knew all of that. Here are some small slogans:

      Check with little examples where you can work out the correct answer quickly: display and Mata are your friends.

      If it does not work as expected, then you probably got it wrong, so test your code to find out. .

      If uncertain, parenthesise aggressively.

      Comment


      • #4
        Thank you Nick!!! Very helpful.

        Comment

        Working...
        X