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
 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.

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.