NaN in R: What is Not a Number Value in R

In R, a numeric variable is either a number (like 1, 2.1, or -3.14) or one of the four special values: NA, NaN, Inf, or -Inf. The Inf and -Inf are positive and negative `infinity‘, whereas NA means “Not Available” and NaN, which we will learn in this tutorial.

NaN in R

NaN in R means “Not a Number” which means there is something or some value, but it cannot be described in the computer. NaN designates a result that cannot be calculated for whatever reason, or it is not a floating-point number.

If you divide 0 / 0, then it will return NaN. The other example is to take a square root of a negative number or perform calculations with infinities that lead to undefined results.

NaN in R is distinct from NA.

rv <- 0 / 0
rv

Output

[1] NaN

As you can see that NaN is usually the product of some arithmetic operation, such as 0/0.

How to check NaN values in R

To check NaN values in R, use the is.nan() function. The is.nan() is a built-in R function that tests the object’s value and returns TRUE if it finds the NaN value; otherwise, it returns FALSE.

rv <- 0 / 0
rv
is.nan(rv)

Output

[1] NaN
[1] TRUE

And we get the TRUE for NaN value. The is.nan() function is provided to check specifically for NaN, and function is.na() also returns TRUE for NaN. Compelling NaN to logical or integer type gives an NA of the appropriate type.

The is.nan() method returns a boolean value for all the components of the vector.

rv2 <- c(100, NaN, 101, 102, 103, NaN)
rv2
is.nan(rv2)

Output

[1] 100 NaN 101 102 103 NaN
[1] FALSE TRUE FALSE FALSE FALSE TRUE

As you can see that it returns TRUE when it finds NaN values; otherwise, FALSE.

Na, NaN, infinity, and -infinity: Table Comparison in R

Function Typical number NA NaN Inf -Inf
is.double() TRUE FALSE TRUE TRUE TRUE
is.finite() TRUE FALSE FALSE FALSE FALSE
is.infinite() FALSE FALSE FALSE TRUE TRUE
is.integer() TRUE (if integer) or FALSE FALSE FALSE FALSE FALSE
is.na() FALSE TRUE TRUE FALSE FALSE
is.nan() FALSE FALSE TRUE FALSE FALSE
is.null() FALSE FALSE FALSE FALSE FALSE
is.numeric() TRUE * TRUE TRUE TRUE

The * represents different values for different circumstances. R has different types of NAs. For example, is.numeric(NA) function returns FALSE, but is.numeric(NA_integer_) and is.numeric(NA_real_) functions return TRUE. Furthermore, is.numeric(NA_complex_) function returns FALSE.

That’s it for this tutorial.

Leave a Comment