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”
# Creating character vector Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
# convert to numeric Vec_num <- as.numeric (Vec)
# display vector print (Vec_num)
|
Output:
Warning message in eval(expr, envir, enclos): "NAs introduced by coercion" [1] 12 12 NA 34 NA
Method 1: Using gsub() method
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
# Creating character vector Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
# replacing non-numeric values with 0 Vec <- gsub ( "Geeks" , "0" , Vec)
# convert to numeric Vec_num <- as.numeric (Vec)
# display vector 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
# Creating character vector Vec <- c ( '12' , '12' , NA , '34' , 'Geeks' )
# convert to numeric suppressWarnings (Vec_num <- as.numeric (Vec))
# display vector print (Vec_num)
|
Output:
[1] 12 12 NA 34 NA