How to correctly convert NaN to NA

r nan 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
Share:
14,269

Related videos on Youtube

Comfort Eagle
Author by

Comfort Eagle

Updated on September 15, 2022

Comments

  • Comfort Eagle
    Comfort Eagle over 1 year

    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?

  • Comfort Eagle
    Comfort Eagle over 6 years
    thanks! Follow up question: What would be the approach for lists?
  • Gregor Thomas
    Gregor Thomas over 6 years
    Nothing special about NA or NaN in a list. Use lapply, sapply, [[, a for loop, whatever you would use normally.