7

I want to check if a variable is '' or 'NULL'. I did below:

x =NULL #or ''

if(is.null(x) || x=='') {
    print('nothing')
} else {
    print(x)
}

My question is what is the best way to check this condition? I feel like there is some better way to do this...

1 Answer 1

4

Rather than check if it is NULL or an empty character string it might make more sense to check if it has a non-zero length and is a string which is not empty. Then the first leg of the if will handle the primary case and the else leg will handle the less common case which seems easier to follow than the other way around.

if (length(x) && nzchar(x)) x else NA
Sign up to request clarification or add additional context in comments.

4 Comments

One drawback is that nzchar(NA) && length(NA) evaluates to TRUE. I know this isn't want the OP wanted.
But that is a different condition, not the one asked for in the question.
Using any(nzchar(x)) might be safer; in some circumstances R complains when you give it a vector of logicals to test.
It depends on what is wanted. If a scalar is expected and a vector is given it would be better to raise an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.