通过强制引入 NA 时如何避免警告 [英] How to avoid warning when introducing NAs by coercion

查看:26
本文介绍了通过强制引入 NA 时如何避免警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常更喜欢对 R 进行编码,这样我就不会收到警告,但我不知道在使用 as.numeric 转换字符向量时如何避免收到警告.

例如:

x <- as.numeric(c("1", "2", "X"))

会给我一个警告,因为它通过强制引入了 NA.我想要通过强制引入的 NA - 有没有办法告诉它是的,这就是我想要做的".还是我应该忍受警告?

或者我应该为此任务使用不同的函数吗?

解决方案

使用 suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))[1] 1 2 不适用

这会抑制警告.

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?

解决方案

Use suppressWarnings():

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

This suppresses warnings.

这篇关于通过强制引入 NA 时如何避免警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆