4

Why does NA==NULL result in logical (0) instead of FALSE?

And why does NULL==NULL result in logical(0) instead of TRUE?

robertspierre
  • 3,218
  • 2
  • 31
  • 46
Tasneema
  • 61
  • 6

1 Answers1

8

NULL is a "zero-length" object, so any elementwise comparison or operation with NULL will have length zero: logical(0) represents a logical vector of length zero. You might find identical() useful: identical(NULL,NULL) is TRUE, identical(NULL,NA) is FALSE. Also see ?is.null, ?is.na for testing for the special values of NA and NULL.

See also: Compare a value to null. Why is this true?

@Dason points out that == does elementwise comparison; when you do elementwise operations on vectors of two different lengths, R typically "recycles" the shorter vector to be equal in length to the longer one (with a warning if the lengths are not evenly divisible), but the R language definition says

As from R 1.4.0, any arithmetic operation involving a zero-length vector has a zero-length result.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 2
    Just to slightly add to the answer - it's useful to remember that == does element-wise comparison. So if you use it to compare two vectors that have length 5; you will get a length 5 vector back. – Dason Sep 28 '19 at 16:58
  • 1
    yes. The slightly weird thing is that if you compare vectors of two different *non-zero* lengths, the shorter one is replicated to the length of the longer one. Admittedly it's impossible to replicate a zero-length vector to a positive length, but it's an edge case whose logic I have trouble explicitly justifying ... – Ben Bolker Sep 28 '19 at 17:02
  • `5 + numeric(0)` returns `numeric(0)`, but `sum(5, numeric(0))` returns `5`. Does this make sense or is this behavior inconsistent? When I saw your answer, I remembered [this answer](https://stackoverflow.com/a/35350139/496488) I wrote a few years ago where this issue came up (see the last paragraph) and I wasn't sure why. – eipi10 Sep 28 '19 at 17:20
  • 1
    I think it's consistent with the R language definition statement above. `+` is an arithmetic operation/operator, `sum()` is a function ... `sum()` *combines* all of its elements (e.g. `sum(5:7,10)` is 28) rather than computing elementwise. – Ben Bolker Sep 28 '19 at 17:23
  • 1
    "`NULL` is a 'zero-length' object" is also demonstrated by `as.numeric(NULL)` OR `as.character(NULL)` OR `as.logical(NULL)` – d.b Sep 28 '19 at 17:26