Reputation: 41
I'm writing some code in r to read excel and send an email upon success. I would like to capture any warnings that are generated when reading the file (e.g. when expecting a date but getting a text) as the file has some inconsistencies so I want to include these warnings as part of the email.
I'm new to R and couldn't find the answer in searching so apologies if this has been answered before.
So far I have tried manipulating the warning messages into a string variable, and it seems to work fine but only when I run a snippet of the code (Ctrl+Enter). If I run all it doesn't capture the warning message.
suppressWarnings(library("readxl"))
success = TRUE
readIssues <- "No file read issues detected"
tryCatch( {
#read excel file
pct <<- read_excel("Filename.xls")
}
, error = function(m) {success <<- FALSE}
)
readIssues <- attr(warnings(),"name")
readIssues <- paste(readIssues,sep=" ",collapse="\n")
I expect readIssues to store the warning messages so I can use them later in the code when generating the email (e.g. "Expecting date in AF1059 / R1059C32: got 'some text'").
I'm curious as to why it runs fine when I select everything and Ctrl+Enter but not when I do Ctrl+Alt+R.
Upvotes: 2
Views: 288
Reputation: 41
The trick was to apply useCallingHandlers within the tryCatch, and then extract the required warning messages. Posting here in case anyone else is looking for the answer:
Credit to this Post
Code:
suppressWarnings(library("readxl"))
success = TRUE
readIssues <- "No file read issues detected"
myWarnings <- NULL
wHandler <- function(w) {
myWarnings <<- c(myWarnings,w)
invokeRestart("muffleWarning")
}
tryCatch( {
pct <- withCallingHandlers(read_excel("Filename.xls"), warning = wHandler)
}
, error = function(m) {success <<- FALSE}
)
pickOut <- sapply(myWarnings, function(x) class(x)=="character")
readIssues <- myWarnings[pickOut]
readIssues <- paste(readIssues,sep="\n",collapse="\n")
Thanks all for the help!
Upvotes: 2