[R] logical operators priority

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Tue Jul 17 10:34:21 CEST 2007

On 17-Jul-07 06:59:11, Delphine Fontaine wrote:
> Dear R-users,
> I haven't found rules for logical operators. I need to select data
> according the following rule:
> Condition A & (Condition B | Condition C)
> How should I write it_? Is Condition A & Condition B | Condition C
> correct or will R execute (Condition A & Condition B) | Condition C ?
> Thanks for your help.
> Delphine Fontaine

?Syntax will tell you about the precedence for operators.
In particular you will find:

       '!'                negation
       '&  &&'            and
       '| ||'             or

indicating that "!" takes precedence over "&" and "&&", which take
precedence over "|" and "||". With equal precedence evaluation is
from left to right.

This shows that if you write A & B | C then "A & B" will be evaluated
first, so the expression is equivalent to (A & B) | C.

In any case, there is nothing whatever wrong with using "(... )"
for grouping. It is always accepted, it forces the precedence you want,
and furthermore (most important) you yourself can see exactly what
will happen and will be much less likely to make a mistake.

So write your condition in your code *explicitly* as

  ConditionA & (ConditionB | ConditionC)

You can see what's happening, and R will do exactly what you want.

Best wishes

E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 17-Jul-07                                       Time: 09:34:18
------------------------------ XFMail ------------------------------

More information about the R-help mailing list