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
.
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"
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())
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With