Comfort Eagle
Comfort Eagle

Reputation: 2452

How to correctly convert NaN to NA

On a given double vector, how come I can define -999 to NA by

v[v == -999] <- NA

but not

v[v == NaN] <- NA

and how do I convert NaN's to NA's correctly?

Upvotes: 9

Views: 15533

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

== doesn't work for testing NA and NaN values. This is good because, from a data perspective, two missing values may or may not be the same. Use is.na() and is.nan() to test for those.

What you want is v[is.nan(v)] <- NA

You can find details in the help pages at ?NaN and ?NA.

This is mentioned on the help pages, but it's worth pointing out that NaN is treated as a special type of NA, so we get this behavior:

> is.na(NaN)
[1] TRUE

> is.nan(NA)
[1] FALSE

Upvotes: 18

Related Questions