NAs introduced by coercion

In the R programming language, this article discusses how to troubleshoot the warning message “NAs introduced by coercion.”

Now we can create an example data.

Random forest machine learning Introduction » finnstats

vectr <- c("14", "53", "1,200", "100", "800", "3,140") 
[1] "14"    "53"    "1,200" "100"   "800"   "3,140"

Take a look at the RStudio console output from before. Our example data is a vector of character strings with six vector elements, as shown.

Decision tree regression and Classification » finnstats

Example: Make a copy of the Warning Message: NAs introduced by coercion

In this example, I’ll show how to use as. numeric function in R to mimic the warning notice “NAs introduced via coercion.” Let’s put the as. numeric function to the test with our example vector:

[1]  14  53  NA 100 800  NA
Warning message:
NAs introduced by coercion

As you can see, the message “NAs introduced by coercion” is displayed, and certain output values are NA (i.e. missing data or not available data).

Linear Discriminant Analysis: A step by step Guide » finnstats

This is because some of the character strings aren’t properly structured integers and so can’t be translated to the numeric class.

The following example demonstrates how to address this problem using R.

Approach 2: Using the gsub() function, modify data to avoid receiving a warning message.

We’ll show you how to deal with the as.numeric() warning notice “NAs introduced by coercion” in approach 2.

As previously stated, some of our input values are improperly formatted due to the presence of commas (i.e.,) between the numbers.

Using the gsub function, we can remove these commas.

new <- gsub(",", "", vectr)  
[1] "14"   "53"   "1200" "100"  "800"  "3140"

Take a look at the previous RStudio console output. It demonstrates that our revised vector is now devoid of commas.

Let’s use the as numeric function once more.

SQL for Data Science Beginners Guide » finnstats

[1]   14   53 1200  100  800 3140

As you can see, we did not only avoid the warning message, we also created an output vector without any NA values.

Approach 2: Using the suppressWarnings() function to disable a warning message

You may not always wish to convert non-number values to numbers. In this scenario, just wrap the suppress warnings function around the as. numeric function to disregard the warning message “NAs introduced by coercion”.

Naive Approach Forecasting Example » finnstats

[1]  14  53  NA 100 800  NA

The output is identical to Example 1, but without the warning notice being printed to the RStudio terminal.

If you know of any other method to handle the same, please comment below.

You may also like...

Leave a Reply

Your email address will not be published.