How to Fix in R: NAs Introduced by Coercion


One common warning message you may encounter in R is:

Warning message:
NAs introduced by coercion 

This warning message occurs when you use as.numeric() to convert a vector in R to a numeric vector and there happen to be non-numerical values in the original vector.

To be clear, you don’t need to do anything to “fix” this warning message. R is simply alerting you to the fact that some values in the original vector were converted to NAs because they couldn’t be converted to numeric values.

However, this tutorial shares the exact steps you can use if you don’t want to see this warning message displayed at all.

How to Reproduce the Warning Message

The following code converts a character vector to a numeric vector:

#define character vector
x <- c('1', '2', '3', NA, '4', 'Hey')

#convert to numeric vector
x_num <- as.numeric(x)

#display numeric vector
x_num

Warning message:
NAs introduced by coercion 
[1]  1  2  3 NA  4 NA

R converts the character vector to a numeric vector, but displays the warning message NAs introduced by coercion since two values in the original vector could not be converted to numeric values.

Method #1: Suppress Warnings

One way to deal with this warning message is to simply suppress it by using the suppressWarnings() function when converting the character vector to a numeric vector:

#define character vector
x <- c('1', '2', '3', NA, '4', 'Hey')

#convert to numeric vector, suppressing warnings
suppressWarnings(x_num <- as.numeric(x))

#display numeric vector
x_num

[1]  1  2  3 NA  4 NA

R successfully converts the character vector to a numeric vector without displaying any warning messages.

Method #2: Replace Non-Numeric Values

One way to avoid the warning message in the first place is by replacing non-numeric values in the original vector with blanks by using the gsub() function:

#define character vector
x <- c('1', '2', '3', '4', 'Hey')

#replace non-numeric values with 0
x <- gsub("Hey", "0", x)

#convert to numeric vector
x_num <- as.numeric(x)

#display numeric vector
x_num

[1]  1  2  3 4 0

R successfully converts the character vector to a numeric vector without displaying any warning messages.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

Leave a Reply

Your email address will not be published.