How to Solve R Warning: NAs Introduced by Coercion

by | Programming, R, Tips

This warning occurs when you try to convert a vector containing non-numeric values to a numeric vector.

As this is a warning, you do not need to solve anything. However, you can replace non-numeric values or suppress the warning using suppressWarnings().

This tutorial will go through the warning and what to do to stop the warning.


Example

Consider the following example where we have a vector of type character. Some of the values have commas between numbers.

vec <- c("10", "1,250", "34", "4,500", "20")
class(vec)
vec
[1] "character"
[1] "10"    "1,250" "34"    "4,500" "20"   

Let’s attempt to convert the character vector to a numeric vector using as.numeric().

vec_new <- as.numeric(vec)
vec_new

Let’s run the code to see the result:

Warning message:
NAs introduced by coercion 

[1] 10 NA 34 NA 20

The warning occurs because R could not convert the two values “1,250” and “4,500” to numeric.

Solution #1: Substitute Non-numeric values

If the data is corrupt, we can replace part or all of the values in the vector so R can convert them to numeric. In this case, we can remove the commas in the values using gsub. Let’s look at the revised code.

vec <- gsub(",", "", vec)
vec_new <- as.numeric(vec)
vec_new

Let’s run the code to see the result:

[1]   10 1250   34 4500   20

We successfully converted the character vector to a numeric vector without displaying the warning message,

Solution #2

We may not want to convert the non-numeric values, in which case we can suppress the warning message using the suppressWarnings() built-in function. Let’s look at the revised code:

vec <- c("10", "1,250", "34", "4,500", "20")
suppressWarnings(vec_new <- as.numeric(vec))
vec_new

Let’s run the code to see the result:

[1] 10 NA 34 NA 20

We successfully converted the character vector to a numeric vector without the warning message.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee