Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get warnings() output to string

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.

like image 704
user2763361 Avatar asked Aug 15 '14 07:08

user2763361


2 Answers

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"
like image 172
Rich Scriven Avatar answered Sep 24 '22 18:09

Rich Scriven


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()).

like image 30
user20637 Avatar answered Sep 22 '22 18:09

user20637