问题
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