How to get warnings() output to string

岁酱吖の 提交于 2021-02-07 07:23:40

问题


When I type warnings() to console, I get back

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

However when I type as.character(warnings()), I get:

[1] "fread(my_directory)"

My objective is to get the actual message displayed in warning() into a character string, so that I can pass it to the logwarn function in the logging package. Currently, I am doing logwarn(warnings(),logger="some_log_file.log") to record my warnings, but it gives the incorrect coercion to character that I displayed above.

Note that I can just use sink but I want to stick with logging package, so I require the ability to correct coerce to character.


回答1:


This may not be the exact answer you're looking for, but I think it's worth a mention.

R has a global variable, last.warning, which holds just that, the last warning. Calling names on it will return the last warning as a character string. Here's a little example

First, purposely trigger a warning:

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

Look at the variable last.warning:

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

Now look at the names(last.warning). This returns the warning as a character string:

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



回答2:


warnings() returns a list. The list values are the language elements which produced the warning; that is what you are seeing with as.character(). The names of the list values are the warning messages. You can get those with names(warnings()).




回答3:


Use a calling handler along with the 'restart' (see ?warning and ?withCallingHandlers) that warning() creates

f = function() { warning("oops"); 1 }

withCallingHandlers({
    f()
}, warning=function(cond) {
    txt <- conditionMessage(cond)
    ## do with txt what you will, e.g.,
    ## logwarn(txt, logger="some_log_file.log")
    message("captured warning: ", txt, "; now continuing")
    ## signal that the warning has been handled
    invokeRestart("muffleWarning")
})


来源:https://stackoverflow.com/questions/25323030/how-to-get-warnings-output-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!