当我输入warnings()进行控制台时,我回来了

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

但是,当我输入as.character(warnings())时,我得到:
[1] "fread(my_directory)"

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

请注意,我只能使用sink,但我想坚持使用logging包,因此我需要能够将强制性更正为character

最佳答案

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

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

查看变量last.warning:
last.warning
# $`the condition has length > 1 and only the first element will be used`
# if (x == 1) "yes" else "no"

现在来看names(last.warning)。这将以字符串形式返回警告:
names(last.warning)
# [1] "the condition has length > 1 and only the first element will be used"

关于r - 如何将warnings()输出到字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25323030/

10-09 19:05