tic-toc-choc
tic-toc-choc

Reputation: 961

Test not NULL and equal to value in R

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?

Upvotes: 2

Views: 266

Answers (1)

akrun
akrun

Reputation: 887048

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)

Upvotes: 3

Related Questions