Compare a value to null. Why is this true?

落花浮王杯 提交于 2019-12-01 15:29:20

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/44774483/compare-a-value-to-null-why-is-this-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!