zesla
zesla

Reputation: 11813

best way to check if an object is null or empty string in r

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...

Upvotes: 7

Views: 3914

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270010

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

Upvotes: 4

Related Questions