Home > Enterprise >  Writing an if statement when the value can be NULL or a string
Writing an if statement when the value can be NULL or a string

Time:07-01

I have a value that can be NULL or a string. The second test fails because a is of length 0. How do I write an if-statement that handles both cases?

Example:

a <- NULL
    
if (is.null(a) | a=="something else then null") {
  print("test")
} 

CodePudding user response:

is.null(a) || a=="something else then null"

(similarly, use && instead of & in a situation like this)

Explanation: when you use |, all conditions are checked one by one and then the "or" assertion is applied. This means that if one of the conditions is invalid, then there is an error, like in your case.

When you use ||, the "or" assertion is checked after each condition check. In your case, is.null(a) is TRUE. This means that is.null(a) "or" any other condition will also be TRUE, so there's no need to check the other condition.

This is based on my understanding of how it works, it's not a definition coming from the docs. I hope it's clearer.

More info: What's the differences between & and &&, | and || in R?

  • Related