Search code examples
rlogical-operatorsoperator-precedencenot-operator

Does operator precedence explain the difference in these expressions involving multiplication of a numeric with a negated logical?


I have three expressions, each involving multiplication with a logical or its negation. These logicals and their negation represent indicator variables, so that the expressions are conditionally evaluated:

-2*3*!T + 5*7*T
5*7*T + -2*3*!T 
(-2*3*!T) + 5*7*T

I expect the above to produce the same result. However:

> -2*3*!T + 5*7*T
[1] 0          # unexpected!
> 5*7*T + -2*3*!T 
[1] 35
> (-2*3*!T) + 5*7*T
[1] 35

I am sure this has something to do with operator precedence and type coercion, but I can't work out how it makes sense to even evaluate !T after the *.


Solution

  • You're exactly right that this is about operator precedence. As ?base::Syntax (which you link above) states, ! has lower precedence than all of the arithmetic operators, so the first expression is equivalent to

    (-2*3)*!(T + 5*7*T)  
    

    (because the expression containing ! has to be evaluated before the final multiplication can be done) or

    -6*!(36)  # T coerced to 1 in numeric operations
    

    or

    -6*FALSE  # non-zero numbers coerced to TRUE in logical operations
    

    or

    -6*0      # FALSE coerced to 0 in numeric operations