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.

You are watching: Warning message: nas introduced by coercion

For example:

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?


*

Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))<1> 1 2 NAThis 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 y 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 = "0" x = as.numeric(x) x = 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

*

Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.

See more: Anne Of Green Gables Season 1 Episode 2, Anne With An E: Season 1 Episode 2

To learn more, see our tips on writing great answers.


Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy


Not the answer you're looking for? Browse other questions tagged r parsing casting na or ask your own question.


R: How to find the mean of a column in a data frame, that has non-numeric (specifically, dashes '-') as well as numeric numbers
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.9.23.40291


Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.