Evaluation of combinations of TRUE and FALSE
It is important to understand how combinations of logical variables evaluate, and to appreciate how logical operations (such as those in Table 2.3) work when there are missing values, NA. Here are all the possible outcomes expressed as a logical vector called x:
x <- c(NA, FALSE, TRUE) names(x) <- as.character(x)
Table 2.3. Logical operations.
| Symbol | Meaning |
| ! | logical NOT |
| & | logical AND |
| | | logical OR |
| < | less than |
| <= | less than or equal to |
| > | greater than |
| >= | greater than or equal to |
| == | logical equals (double =) |
| != | not equal |
| && | AND with IF |
| || | OR with IF |
| xor(x,y) | exclusive OR |
| isTRUE(x) | an abbreviation of identical(TRUE,x) |
To see the logical combinations of & (logical AND) we can use the outer function with x to evaluate all nine combinations of NA, FALSE and TRUE like this:
outer(x, x, "&")
<NA> FALSE TRUE
<NA> NA FALSE NA
FALSE FALSE FALSE FALSE
TRUE NA FALSE TRUE
Only TRUE & TRUE evaluates to TRUE. Note the behaviour of NA & NA and NA & TRUE. Where one of the two components is NA, the result will be NA if the outcome is ambiguous. Thus, NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE. To see the logical combinations of | (logical OR) write
outer(x, x, "|")
<NA> FALSE TRUE
<NA> NA NA TRUE
FALSE NA FALSE TRUE
TRUE TRUE TRUE TRUE
Only FALSE | FALSE evaluates to FALSE. Note the behaviour of NA | NA and NA | FALSE.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access