Posted on by Zach
In R, NaN stands for Not a Number.
Typically NaN values occur when you attempt to perform some calculation that results in an invalid result.
For example, dividing by zero or calculating the log of a negative number both produce NaN values:
#attempt to divide by zero0 / 0[1] NaN#attempt to calculate log of negative valuelog(-12)[1] NaN
Note that NaN values are different from NA values, which simply represent missing values.
You can use the following methods to handle NaN values in R:
#identify positions in vector with NaN valueswhich(is.nan(x))#count total NaN values in vectorsum(is.nan(x)) #remove NaN values in vectorx_new <- x[!is.nan(x)]#replace NaN values in vectorx[is.nan(x)] <- 0
The following examples show how to use each of these methods in practice.
Example 1: Identify Positions in Vector with NaN Values
The following code shows how to identify the positions in a vector that contain NaN values:
#create vector with some NaN valuesx <- c(1, NaN, 12, NaN, 50, 30)#identify positions with NaN valueswhich(is.nan(x))[1] 2 4
From the output we can see that the elements in positions 2 and 4 in the vector are NaN values.
Example 2: Count Total NaN Values in Vector
The following code shows how to count the total number of NaN values in a vector in R:
#create vector with some NaN valuesx <- c(1, NaN, 12, NaN, 50, 30)#identify positions with NaN valuessum(is.nan(x))[1] 2
From the output we can see that there are 2 total NaN values in the vector.
Example 3: Remove NaN Values in Vector
The following code shows how to create a new vector that has the NaN values removed from the original vector:
#create vector with some NaN valuesx <- c(1, NaN, 12, NaN, 50, 30)#define new vector with NaN values removedx_new <- x[!is.nan(x)]#view new vectorx_new[1] 1 12 50 30
Notice that both NaN values have been removed from the vector.
Example 4: Replace NaN Values in Vector
The following code shows how to replace NaN values in a vector with zeros:
#create vector with some NaN valuesx <- c(1, NaN, 12, NaN, 50, 30)#replace NaN values with zerox[is.nan(x)] <- 0#view updated vectorx[1] 1 0 12 0 50 30
Notice that both NaN values have been replaced by zeros in the vector.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Interpolate Missing Values in R
How to Find and Count Missing Values in R
How to Use “Is Not NA” in R