**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:

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

```
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.

```
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**.

```
# 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.

```
# 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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.