is.nan()

is.nan(x)
Returns: logical · Updated March 13, 2026 · Base Functions
nan missing-values type-checking base

The is.nan() function tests whether elements in an object are NaN (Not a Number). NaN represents an undefined or unrepresentable value, such as the result of 0/0.

Syntax

is.nan(x)

Parameters

ParameterTypeDefaultDescription
xany objectObject to test for NaN values

Examples

Basic usage

# Division resulting in NaN
x <- 0 / 0
is.nan(x)
# [1] TRUE

# Square root of negative number
y <- sqrt(-1)
is.nan(y)
# [1] TRUE

NaN vs NA vs NULL

# NaN is a special value
x1 <- NaN
is.nan(x1)   # [1] TRUE
is.na(x1)    # [1] TRUE  (NaN is also considered NA)
is.null(x1)  # [1] FALSE

# NA is missing
x2 <- NA
is.nan(x2)   # [1] FALSE
is.na(x2)    # [1] TRUE
is.null(x2)  # [1] FALSE

# NULL is absence of value
x3 <- NULL
is.nan(x3)   # [1] FALSE
is.na(x3)    # [1] FALSE
is.null(x3)  # [1] TRUE

Operations producing NaN

# Various NaN-producing operations
is.nan(0 / 0)
# [1] TRUE

is.nan(sqrt(-1))
# [1] TRUE

is.nan(log(-1))
# [1] TRUE

is.nan(Inf - Inf)
# [1] TRUE

Common Patterns

Handling NaN in computations

# Replace NaN with NA or a default value
x <- c(1, 2, NaN, 4, NaN)
x[is.nan(x)] <- NA
x
# [1]  1  2 NA  4 NA

# Using ifelse
x <- c(1, 2, NaN, 4)
ifelse(is.nan(x), 0, x)
# [1] 1 2 0 4

Cleaning numeric data

# Check for any NaN in data
data <- c(1, 2, NaN, 4, 5)
any(is.nan(data))
# [1] TRUE

# Remove NaN
data[!is.nan(data)]
# [1] 1 2 4 5

Numerical analysis

# Checking for undefined results
calculate <- function(x) {
  if (x < 0) {
    return(NaN)
  }
  sqrt(x)
}

sapply(c(4, 0, -4), calculate)
# [1]  2  0 NaN

See Also