根据警告在警告列表中的位置或基于R中的正则表达式禁止警告

问题描述 投票:0回答:1

我使用的一个功能可以返回警告:第一个警告一直在发生,我不在乎。通常要注意以下警告,因为它们实际上警告某些地方确实出了问题。

这里是我不关心的函数返回的通常警告的示例:

Warning message:
Using alpha for a discrete variable is not advised.

这是通常的警告示例+我实际上想看到它何时返回的相关警告:

Warning messages:
1: Using alpha for a discrete variable is not advised. 
2: Removed 2 rows containing missing values (geom_point).

我的问题是,如何基于警告列表中的位置或使用正则表达式或任何其他主意,而不使用默认R包之外的其他任何方式禁止第一条警告(Using alpha for a discrete variable is not advised.) (基础,数据集,图形,统计信息...)?

到目前为止,我发现的解决方案使用了具有自己的suppress_warnings()函数的程序包pkgcond v0.1.0。但我真的想避免加载其他软件包。

谢谢您的帮助!

r warnings suppress-warnings
1个回答
1
投票

这里是处理问题的一种方法。

让我们从一个返回所需值的函数开始,但在这样做之前会抛出两个警告:

make_warnings <- function()
{
  warning("This is a warning that can be ignored")
  warning("This is a warning that shouldn't be ignored")
  return(0)
}

当然,如果运行此命令,则会收到警告:

make_warnings()
#> [1] 0
#> Warning messages:
#> 1: In make_warnings() : This is a warning that can be ignored
#> 2: In make_warnings() : This is a warning that shouldn't be ignored

但是我们可以使用withCallingHandlers处理警告。我们需要做的就是设置一个函数,该函数使用带grepl的正则表达式检查任何特定警告的内容,并在得到正则表达式匹配时禁止显示警告:

warning_handler <- function(w)
{
  condition <- conditionMessage(w)
  if(grepl("can be ignored", condition)) invokeRestart("muffleWarning")
}

所以现在我们可以运行警告生成功能,只是使我们不关心的警告静音。

withCallingHandlers(make_warnings(), warning = warning_handler)
#> [1] 0
#> Warning message:
#> In make_warnings() : This is a warning that shouldn't be ignored
© www.soinside.com 2019 - 2024. All rights reserved.