NaN in R: Not a Number Value and is.nan() Method

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

In R, NaN means “Not a Number,” which means there is something or some value, but it cannot be described in the computer. NaN is distinct from NA. 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.

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 an inbuilt R function that tests R 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

FunctionTypical numberNANaNInf-Inf
is.double()TRUEFALSETRUETRUETRUE
is.finite()TRUEFALSEFALSEFALSEFALSE
is.infinite()FALSEFALSEFALSETRUETRUE
is.integer()TRUE (if integer) or FALSEFALSEFALSEFALSEFALSE
is.na()FALSETRUETRUEFALSEFALSE
is.nan()FALSEFALSETRUEFALSEFALSE
is.null()FALSEFALSEFALSEFALSEFALSE
is.numeric()TRUE*TRUETRUETRUE

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