Select Page

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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!