10

Why is

isTRUE(NULL != 2)
[1] FALSE

And how would I receive TRUE?

In my real case I have variables and I want to process something, if the values differ. However, when one value is NULL I don't recognize them as different!

zx8754
  • 52,746
  • 12
  • 114
  • 209
agoldev
  • 2,078
  • 3
  • 23
  • 38
  • 8
    You can't compare with NULL. You need is.null to test if something is a reference to the NULL object. – Roland Jun 27 '17 at 07:28
  • To get the value you expect you would: `isTRUE(!is.null(2))` – Carles Mitjans Jun 27 '17 at 07:31
  • @CarlesMitjans the variable is not always NULL, normally it has another integer value. It's only rarely that it has NULL. It's inconvenient, but I added another is.null() check before. I don't get this, though. Other languages do fine here. – agoldev Jun 27 '17 at 07:32
  • related: https://stackoverflow.com/q/28502037/4137985 – Cath Jun 27 '17 at 07:36
  • Possible duplicate of https://stackoverflow.com/questions/10592148/compare-if-two-dataframe-objects-in-r-are-equal – akrun Jun 27 '17 at 07:39
  • Does this answer your question? [Compare if two dataframe objects in R are equal?](https://stackoverflow.com/questions/10592148/compare-if-two-dataframe-objects-in-r-are-equal) – philipxy Sep 30 '22 at 18:49

2 Answers2

13

As @Roland pointed out, we can't perform any logical operations directly on NULL object. To compare them we might need to perform an additional check of is.null and then perform the logical comparison.

We can use identical instead to compare values which handles integers as well as NULL.

identical(4, 2) 
#FALSE

identical(NULL, 2) 
#FALSE

identical(2, 2) 
#TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

In order to answer the why part of your question:

Comparing NULL with other types will give you logical(0) (i.e., a logical vector of length zero). So,

isTRUE(NULL != 2)

actually is

isTRUE(logical(0))

which is FALSE.

In order to compare the values where you might have NULL values also, you could also do something like this (using short circuit logical operator):

a <- 2
b <- 2
!is.null(a) && !is.null(b) && a==b
#[1] TRUE

a <- 3
b <- 2
!is.null(a) && !is.null(b) && a==b
#[1] FALSE

a <- 2
b <- NULL
!is.null(a) && !is.null(b) && a==b
#[1] FALSE
989
  • 12,579
  • 5
  • 31
  • 53