4

I first wondered why FALSE | NA returns
#> [1] NA, while
TRUE | NA returns
#> [1] TRUE.

Then I read the explanation that "because the value of the missing element matters in NA | FALSE, these are missing".
So I tried TRUE | FALSE and FALSE | TRUE. And indeed, both return #>[1] TRUE.
It makes sense that because the result of NA | FALSE depends on the value of NA, it returns NA, while the value of NA does not really matter for NA | TRUE to be TRUE.
However, can someone explain why TRUE | FALSE returns TRUE?
Thank you!

Cath
  • 23,906
  • 5
  • 52
  • 86
Ane
  • 335
  • 1
  • 11

2 Answers2

4

Essentially, it asks whether at least one side is TRUE. As there is one TRUE value, the result is also TRUE.

It is the same as with:

1 > 0 | 0 > 2
[1] TRUE

Conversely, when it asks whether all sides are TRUE:

TRUE & FALSE
[1] FALSE

As with the numerical example:

1 > 0 & 0 > 2
[1] FALSE
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
  • Nice. This also explains the `&` operator and why `TRUE & FALSE` returns `FALSE`... – Sotos Jan 15 '20 at 07:46
  • Great! Thanks. I still wonder a bit why it is that "at least one side" has to be TRUE to return TRUE. Why not "at least one side" has to be FALSE to return FALSE? .. But I'm satisfied with this answer for now :) – Ane Jan 15 '20 at 07:55
  • Maybe it has a serious explanation (like when `TRUE` is converted to a numeric value, then it is represented as `1`, so it has priority over `FALSE` which is represented as `0`), but I think it is mostly convention (even the assignment of `0`/`1` is) :) – tmfmnk Jan 15 '20 at 08:01
1

For the operation |, the output is TRUE as long as at least one of its condition is TRUE. For instance TRUE | FALSE| FALSE | FALSE gives TRUE, but FALSE | FALSE| FALSE | FALSE gives FALSE since it has no TRUE condition.

Since NA could be TRUE or FALSE, but you don't know what it exactly is.

  • In this sense, FALSE | NA might be equivalent to FALSE | TRUE (which gives TRUE) or FALSE | FALSE (which gives FALSE), which are two possibilities and still not available, so FALSE | NA returns NA.

  • However, for TRUE | NA, it is always TRUE since it is not depends on NA (NA as either TRUE or FALSE does not affects the result)

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • From the R documentation: "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. " – otwtm Jan 15 '20 at 07:48
  • @otwtm yes, this is as explained in my answer – ThomasIsCoding Jan 15 '20 at 07:55
  • yes, just wanted to back up your answer with reference :) – otwtm Jan 15 '20 at 08:24