I would like to use the warning handler function in tryCatch() to print all of the warning messages generated by the expression raw_data <- readxl::read_excel(file_path)
in an R package I am developing. The code below, when executed as part of the package:
get_col_types <- function(ver){
if (ver == 2) {
raw_col_types <- rep("text", times = 35)
raw_col_types[c(1,3,5,19:31,33)] <- "numeric"
}
else {
raw_col_types <- rep("text", times = 31)
raw_col_types[c(1,16:27,29)] <- "numeric"
}
return(raw_col_types)
}
tryCatch(raw_data <- readxl::read_excel(file_path, col_types = get_col_types(2)),
warning = function(w) {
print(paste('WARNING MESSAGE: ', w$message))
},
finally = "Input processed")
Produces this output, which only contains the first warning generated by the expression:
[1] "WARNING MESSAGE: Coercing text to numeric in AD89 / R89C30: '0.002'"
However, running the below lines in the RStudio console (outside of the package):
options(warn = 1)
raw_data <- readxl::read_excel(file_path)
Produces a complete listing of all warnings generated while reading the excel file:
Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
Coercing text to numeric in AD89 / R89C30: '0.002'
Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
Expecting numeric in C622 / R622C3: got 'NA'
Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
Expecting numeric in C626 / R626C3: got 'ghiuek'
I had previously attempted to set options(warn = 1)
for the package within an .onLoad()
function, but this was unsuccessful. Is there any way to print all of the warnings generated by this expression, ideally by getting the warning handler function to execute only after the last warning is generated by the expression (rather than having it execute immediately after the first warning is generated)?