Cor*_*one 112 parsing casting r na
我通常更喜欢编码R,以便我不会收到警告,但我不知道在使用as.numeric转换字符向量时如何避免收到警告.
例如:
x <- as.numeric(c("1", "2", "X"))
Run Code Online (Sandbox Code Playgroud)
会给我一个警告,因为它通过强制引入了NA.我希望通过强制来引入NA - 有没有办法告诉它"是的,这就是我想做的事情".或者我应该接受警告?
或者我应该使用不同的功能来执行此任务?
And*_*rie 132
用途suppressWarnings():
suppressWarnings(as.numeric(c("1", "2", "X")))
[1] 1 2 NA
Run Code Online (Sandbox Code Playgroud)
这抑制了警告.
Ari*_*man 32
suppressWarnings()已被提及.另一种方法是首先手动将有问题的字符转换为NA.对于您的特定问题,taRifx::destring就是这样.这样,如果您从函数中获得其他意外警告,则不会被抑制.
> 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
Run Code Online (Sandbox Code Playgroud)
jan*_*cki 19
通常,抑制警告不是最佳解决方案,因为您可能希望在提供某些意外输入时收到警告.
下面的解决方案是在数据类型转换期间仅保持NA的包装器.不需要任何包装.
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
Run Code Online (Sandbox Code Playgroud)