禁止单个警告/错误消息

时间:2014-04-11 13:47:39

标签: r warnings suppress-warnings

我想阻止某个功能警告我。

>for (v in c("1", "a2", "aaa", 10)) 
  if (is.na(as.numeric(v))) 
    cat("\nWarning:", paste(v, "cannot be coerced into a number"))

Warning: a2 cannot be coerced into a number
Warning: aaa cannot be coerced into a number
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion

我希望只显示我的警告:Warning: a2 cannot be coerced into a numberWarning: aaa cannot be coerced into a number

我认为有两种方法可以做到这一点 1.覆盖R使用的警告。 2.取消R使用的警告。

任何一方的帮助都会提供信息,但我对抑制警告系统更感兴趣。

感谢您提供的任何帮助! 弗朗西斯

1 个答案:

答案 0 :(得分:3)

你走了:

for (v in c("1", "a2", "aaa", 10)) 
    if (is.na(suppressWarnings(as.numeric(v))))
        warning(paste(v, "cannot be coerced into a number"))

suppressWarnings评估表达式并忽略警告。

warning生成您自己的警告:)