This question is similar, but different from Disregarding simple warnings/errors in tryCatch. I am reading an Excel file from an external source over which I have no control. I frequently encounter one of more warnings when it's reading scientific notation. Since the read_excel file handles these well, I'd like to ignore those warnings but display any others that might be generated. Here is some data in a CSV format.
V1,V2,V3,V4
A,0,0,Include
B,0,0,Include
C,0,-2.0484947071963688E-11,Include
D,0,-9.1299973,Include
E,1.8488805068272995E-05,0,Include
F,0.003399333,0,Include
G,-9.902539136998455E-05,0,Include
H,-0.000442444,0,Include
I,-4.561459166153803E-05,0,Include
J,-0.00095274,0,Include
Let's say those 4 columns and 10 rows are in an Excel file called 'example.xlsx'. The following code will generate 4 warnings to the effect that it is "Coercing text to numeric" which is related to rows C, E, G, and I being in scientific notation.
readxl::read_excel("example.xlsx", .name_repair = "unique",
col_types = c("guess",
rep("numeric", 2),
"guess"))
The length(warnings()
will be 4. I would like to suppress warnings of this type and pass through other warnings (and errors). If the warnings are only of this type ("Coercing text to numeric") then I want to return the results of the function because it converts those values fine.
I'm stuck on tryCatch (and lost on withCallingHandlers). The warning_message created by the tryCatch function seems to only catch the first warning and not all of them. Also, when there are only the warning I want to ignore, can I return the results of the read_excel function (without having to call the function a second time?
Here is a concept of what I'd like to accomplish. First, here's a function which would help if I could access the warnings() function within tryCatch.
ignoreWarnings <- function(w){
for(i in names(w)){
if(regexpr("Coercing text to numeric", i) == -1) return(FALSE)
}
return(TRUE)
}
Then the tryCatch might look like this:
tryCatch(out <- readxl::read_excel("example.xlsx", .name_repair =
"unique",
col_types = c("guess",
rep("numeric", 2),
"guess")),
error = function(error_message){
message(error_message)
return(NA)
},
warning = function(warning_message){
if(ignoreWarnings(warning_message)){
return(out)
} else {
message(warning_message)
return(NA)
}
}
)
In the case where ignoreWarnings is TRUE, we return out
which is the result of the read_excel function as if there were no errors or warnings. If FALSE, we pass through the warnings and return NA.
I realize the warning_message
is different from warnings(). I don't seem to be able to access warnings() in tryCatch. It would be nice to avoid having to call the read_excel twice in the case there are only warnings to be ignored.