How to correctly convert NaN to NA
14,269
==
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
Related videos on Youtube
Author by
Comfort Eagle
Updated on September 15, 2022Comments
-
Comfort Eagle over 1 year
On a given double vector, how come I can define
-999
toNA
byv[v == -999] <- NA
but not
v[v == NaN] <- NA
and how do I convert
NaN
's toNA
's correctly? -
Comfort Eagle over 6 yearsthanks! Follow up question: What would be the approach for lists?
-
Gregor Thomas over 6 yearsNothing special about
NA
orNaN
in a list. Uselapply
,sapply
,[[
, a for loop, whatever you would use normally.