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”.
When you call a function with an argument of the wrong type, R will try to coerce values to a different type so that the function will work. There are two types of coercion that occur automatically in R: coercion with formal objects and coercion with built-in types.
The as. numeric in R is a built-in method that returns a numeric value. The as. numeric() function takes an R object that needs to be coerced and returns the converted numeric value.
Use suppressWarnings()
:
suppressWarnings(as.numeric(c("1", "2", "X")))
[1] 1 2 NA
This suppresses warnings.
suppressWarnings()
has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring
does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.
> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion
> y <- destring(c("1", "2", "X"))
> y
[1] 1 2 NA
> x
[1] 1 2 NA
In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.
as.num = function(x, na.strings = "NA") {
stopifnot(is.character(x))
na = x %in% na.strings
x[na] = "0"
x = as.numeric(x)
x[na] = NA_real_
x
}
as.num(c("1", "2", "X"), na.strings="X")
#[1] 1 2 NA
I have slightly modified the jangorecki function for the case where we may have a variety of values that cannot be converted to a number. In my function, a template search is performed and if the template is not found, FALSE is returned.! before gperl, it means that we need those vector elements that do not match the template. The rest is similar to the as.num
function. Example:
as.num.pattern <- function(x, pattern){
stopifnot(is.character(x))
na = !grepl(pattern, x)
x[na] = -Inf
x = as.numeric(x)
x[na] = NA_real_
x
}
as.num.pattern(c('1', '2', '3.43', 'char1', 'test2', 'other3', '23/40', '23, 54 cm.'))
[1] 1.00 2.00 3.43 NA NA NA NA NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With