How do you fix NAs introduced by coercion?

Coercion in data analysis is the process of changing the type of a variable. To fix NAs introduced by coercion, one should check the data type of the variable before coercing it to another type and look for any existing NA values. If any exist, one should decide whether to replace the NAs with an appropriate value or to drop them. Additionally, it is also important to check the data structure of the variable, as coercing a variable to an inappropriate type may lead to unintended results.


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.

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

How to Fix in R: longer object length is not a multiple of shorter object length

x