I generally prefer to code R so that I don't get warnings, but I don't know how to avoid getting a warning when using as.numeric
to convert a character vector.
For example:
x <- as.numeric(c("1", "2", "X"))
Will give me a warning because it introduced NAs by coercion. I want NAs introduced by coercion - is there a way to tell it "yes this is what I want to do". Or should I just live with the warning?
Or should I be using a different function for this task?
You can use the library
stringr
.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.
Use
suppressWarnings()
: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.