Warning message: NAs introduced by coercion in R (Example)

On this page you’ll learn how to reproduce and debug the warning message: “NAs introduced by coercion” in the R programming language.

Example Data

In this tutorial, we’ll use the following vector object to illustrate the warning message.

x <- c("1", "7", "y", "5", "3", "2,5")
x
## [1] "1"   "7"   "y"   "5"   "3"   "2,5"

Reproduce the Warning Message

The R code below replicates the warning message.

as.numeric(x)
## Warning: NAs introduced by coercion
## [1]  1  7 NA  5  3 NA

Why the Warning Message Occurrs

The reason for the occurrence of the warning message is that our input vector contains two values that cannot be converted to the numeric class.

The first of these values is the letter “y”. Such letters cannot be transformed to numeric, simply because they are no numbers.

The second of these values is the number “2,5”. Note that this number has a decimal comma instead of a decimal point as separator. This is problematic when converting data to numeric.

Debug the Warning Message

The R code below fixes the warning message.

First, we remove the character letter “y”. Then, we replace the decimal comma by a decimal point.

x2 <- x
x2 <- x2[- 3]
x2 <- gsub(",", "\\.", x2)
x2
## [1] "1"   "7"   "5"   "3"   "2.5"

In the next step, we can apply the as.numeric function to convert our data:

x2_num <- as.numeric(x2)
x2_num
## [1] 1.0 7.0 5.0 3.0 2.5

No warning messages occur anymore.

Let’s check the class of our new data object x_num:

class(x2_num)
## [1] "numeric"

Our new data object has the numeric class.