How to avoid warning when introducing NAs by coercion

筅森魡賤 提交于 2019-11-26 09:16:54

问题


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?


回答1:


Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))
[1]  1  2 NA

This suppresses warnings.




回答2:


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



回答3:


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



回答4:


I had the same issue with a data frame column I wanted to use for the y-axis of a ggplot2 scatterplot but here is how I solved it:

as.numeric(as.factor(columnName))

You might find this helpful too instead of using suppressWarnings()



来源:https://stackoverflow.com/questions/14984989/how-to-avoid-warning-when-introducing-nas-by-coercion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!