How to Fix: NAs Introduced by Coercion in R
In this article, we are going to see how Fix: NAs Introduced by Coercion in R Programming Language.
Produce the error
“NAs Introduced by Coercion” error occurs due to replacing the value in a vector with another value that “has length zero”
R
Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
Vec_num <- as.numeric (Vec)
print (Vec_num)
|
Output:
Warning message in eval(expr, envir, enclos):
"NAs introduced by coercion"
[1] 12 12 NA 34 NA
Here we will use gsub() method to replace the non-numeric value with 0. gsub() function in R Language is used to replace all the matches of a pattern from a string.
Syntax: gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
Parameters:
- pattern: string to be matched
- replacement: string for replacement
- string: String or String vector
- ignore.case: Boolean value for case-sensitive replacement
R
Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
Vec <- gsub ( "Geeks" , "0" , Vec)
Vec_num <- as.numeric (Vec)
print (Vec_num)
|
Output:
[1] 12 12 NA 34 0
Method 2: Using suppressWarnings() method
Here we will use suppressWarnings() methods which are used to suppress the warnings.
Syntax: suppressWarnings(arg)
Where arg can be the warning
R
Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
suppressWarnings (Vec_num <- as.numeric (Vec))
print (Vec_num)
|
Output:
[1] 12 12 NA 34 NA
Last Updated :
08 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...