Compare a value to null. Why is this true?

后端 未结 2 1198
野的像风
野的像风 2021-01-17 16: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,

2条回答
  •  Happy的楠姐
    2021-01-17 16:31

    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
    

提交回复
热议问题