NaN in R: Creating, Checking, Counting and Removing NaN Values

NaN in R stands for “Not a Number, and is used whenever the data is missing.

NaN is different from NA.

Here are some examples of values that NaN represents:

  1. Division by zero
  2. The square root of a negative number
  3. The logarithm of a negative number
  4. The result of a floating-point operation that overflows or underflows
  5. A floating-point value that is not representable in the IEEE 754 standard

NaN in R

vec <- 0 / 0

vec

Output

[1] NaN

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

Checking NaN Value

To check NaN values, use the “is.nan()” function. It returns TRUE if the value is NaN and FALSE otherwise.

Checking NaN Value in R

vec <- 0 / 0

is.nan(vec)

Output

[1] TRUE

Counting NaN values

To count the number of NaN values, you can use the is.nan() function combined with the sum() function.

vec <- c(19, 21, NaN, 46, NaN)

# Counting NaN values
nan_count <- sum(is.nan(vec))

# Print the count
print(nan_count)

Output

[1] 2

Removing NaN Values

The code df[!is.nan(x)] will select all of the elements of x that are not NaN.

The is.nan() function is used to check if a value is NaN.

The “!” operator is used to invert the result of a logical operation.

Removing NaN values from vector in R

# Create a vector with some NaN values.
vec <- c(19, 21, NaN, 46, NaN)

# Remove the NaN values.
na_free_vec <- vec[!is.nan(vec)]

# Print the vector.
print(na_free_vec)

Output

[1] 19 21 46

Replacing NaN Values with 0

To replace NaN values with 0, use is.nan() function.

Replacing NaN Values with 0 in R

# Create a vector with some NaN values.
vec <- c(19, 21, NaN, 46, NaN)

# Replace all NaN values with 0
vec[is.nan(vec)] <- 0
print(data)

Output

[1] 19 21 0 46 0

We are replacing all NaN values in vec with 0 using the logical indexing is.nan(vec) function.

NA, NaN, infinity, and -infinity: Table Comparison

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.

That’s all!

Leave a Comment