Home > Blockchain >  Test not NULL and equal to value in R
Test not NULL and equal to value in R

Time:02-02

Is there a command in R to check if a variable that could possibly be NULL is equal to a value (e.g. "hello")

Since:

x <- NULL
if (x == "hello") print(x)

is an error, I have to go into two steps:

if (!is.null(x)) {
  if (x == "hello") print(x)
}

Is there a way to perform this test "not NULL and equal to value" in one command?

CodePudding user response:

We can use a short-circuit with && - the advantage is that the second expression (x == "hello") only gets evaluated if the first is TRUE - thus avoiding the error from evaluating the second expression when the value is NULL

x <- NULL
if(!is.null(x) && x == "hello") print(x)
  •  Tags:  
  • r
  • Related