How to correctly convert NaN to NA
Asked Answered
A

1

9

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?

Aer answered 28/7, 2017 at 15:24 Comment(0)
R
18

== 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
Rupertruperta answered 28/7, 2017 at 15:27 Comment(2)
thanks! Follow up question: What would be the approach for lists?Aer
Nothing special about NA or NaN in a list. Use lapply, sapply, [[, a for loop, whatever you would use normally.Rupertruperta

© 2022 - 2024 — McMap. All rights reserved.