如何将警告()输出到字符串

use*_*361 5 error-handling logging warnings r try-catch

当我输入警告()到控制台时,我回来了

Warning message:
In fread(my_directory,  ... :
 C function strtod() returned ERANGE for one or more fields. The first was string input    '4.40589099726375E-309'. It was read using (double)strtold() as numeric
Run Code Online (Sandbox Code Playgroud)

但是,当我输入时as.character(warnings()),我得到:

[1] "fread(my_directory)"
Run Code Online (Sandbox Code Playgroud)

我的目标是将warning() 中显示的实际消息转换为字符串,以便我可以将其传递给包中的logwarn函数logging。目前,我正在logwarn(warnings(),logger="some_log_file.log")记录我的警告,但它给了character我上面显示的错误强制。

请注意,我可以只使用sink但我想坚持使用logging包,所以我需要能够更正强制到character.

Ric*_*ven 6

这可能不是您正在寻找的确切答案,但我认为值得一提。

R 有一个全局变量 ,last.warning它保存的是最后一个警告。调用names它将以字符串形式返回最后一个警告。这是一个小例子

首先,故意触发警告:

x <- 1:5
if(x == 1) "yes" else "no"
# [1] "yes"
# Warning message:
# In if (x == 1) "yes" else "no" :
#   the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)

查看变量last.warning

last.warning
# $`the condition has length > 1 and only the first element will be used`
# if (x == 1) "yes" else "no"
Run Code Online (Sandbox Code Playgroud)

现在看看names(last.warning). 这将警告作为字符串返回:

names(last.warning)
# [1] "the condition has length > 1 and only the first element will be used"
Run Code Online (Sandbox Code Playgroud)


use*_*637 2

warnings()返回一个列表。列表值是产生警告的语言元素;这就是你所看到的as.character()。列表值的名称是警告消息。你可以通过names(warnings()).