What is NaN in R

NaN in R stands for “Not a Number” and is a special value used to represent undefined or unrepresentable numerical values. For example, dividing by zero or calculating the log of a negative number both produce NaN values.

NaN means there is something or some value that cannot be described in the computer. It designates a result that cannot be calculated for whatever reason or is not a floating-point number.

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 for 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 the NaN value. The is.nan() function is provided to check specifically for NaN, and the 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 vector components.

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

NaN in R is distinct from NA.

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.

Leave a Comment