Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly convert NaN to NA

Tags:

r

nan

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?

like image 355
Comfort Eagle Avatar asked Jul 28 '17 15:07

Comfort Eagle


People also ask

What is the difference between NA and NaN in R?

In R, missing values are represented by the symbol NA (not available). Impossible values (e.g., dividing by zero) are represented by the symbol NaN (not a number). Unlike SAS, R uses the same symbol for character and numeric data.

How do I replace NANS in R?

Replace NA with 0 in R Data Frame In this tutorial, we will learn how to replace all NA values in a data frame with zero number in R programming. To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.

How do I remove NaN in R?

The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na. omit.


1 Answers

== 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
like image 171
Gregor Thomas Avatar answered Sep 19 '22 16:09

Gregor Thomas