3.4 Logical operations

3.4.1 Vectorized logical operations:

TRUE and FALSE can also be a result of a “predicate”:

== and > (and co.) only accept two arguments (binary operators):

We need to use logical operators (help("Logic")).

Logical operators:

  • ! not (Unary)

  • & and: are both true

  • | or: at least one true

  • xor exclusive-or: one and only one is true

(We will see their scalar counter part in chapter 8)

Those operators have lower precedence than the arithmetic so they are quite intuitive (except maybe !)

3.4.2 missingness

  • NA | TRUE -> TRUE (this one is easy)

  • NA | FALSE -> NA because it depend on what NA could be

(in doubt build a quick truth tables)

3.4.3 Aggregating with all, any and sum

  • all() test if all elements match

  • any() test if at least one match

  • sum() use the trick that FALSE is 0 and TRUE is 1

sum(runif(10000) >= .2)
## [1] 7995

3.4.4 Simplify predicates

You should think about it!

  • a > b | a <= b : this one is obvious (but I could have done it!)

some are less obvious.