27

I cannot understand the properties of logical (boolean) values TRUE, FALSE and NA when used with logical OR (|) and logical AND (&). Here are some examples:

NA | TRUE
# [1] TRUE

NA | FALSE
# [1] NA

NA & TRUE
# [1] NA

NA & FALSE
# [1] FALSE

Can you explain these outputs?

Jaap
  • 81,064
  • 34
  • 182
  • 193
Remi.b
  • 17,389
  • 28
  • 87
  • 168

2 Answers2

33

To quote from ?Logic:

NA is a valid logical object. Where a component of x or y is NA, the result will be NA if the outcome is ambiguous. In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE. See the examples below.

The key there is the word "ambiguous". NA represents something that is "unknown". So NA & TRUE could be either true or false, but we don't know. Whereas NA & FALSE will be false no matter what the missing value is.

joran
  • 169,992
  • 32
  • 429
  • 468
14

It's explained in help("|"):

NA is a valid logical object. Where a component of x or y is NA, the result will be NA if the outcome is ambiguous. In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE. See the examples below.

From the examples in help("|"):

x <- c(NA, FALSE, TRUE)
names(x) <- as.character(x)
outer(x, x, "&") ## AND table
#        <NA> FALSE  TRUE
# <NA>     NA FALSE    NA
# FALSE FALSE FALSE FALSE
# TRUE     NA FALSE  TRUE

outer(x, x, "|") ## OR  table
#        <NA> FALSE TRUE
#  <NA>    NA    NA TRUE
# FALSE    NA FALSE TRUE
#  TRUE  TRUE  TRUE TRUE
Henrik
  • 65,555
  • 14
  • 143
  • 159
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418