0

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)?

  • 1
    Check out this answer: https://stackoverflow.com/a/40572658/2372064 – MrFlick Jul 14 '20 at 17:27
  • @MrFlick I agree; put in a close vote in favor of that question. – Carl Witthoft Jul 14 '20 at 17:50
  • @charlyPhillips, if you don't like the referenced answer, add some explanation and I will re-open. In the meantime, consider whether it is truly useful for you to get multiple warning reports, and if so whether you might issue multiple calls to `read_excel` , perhaps one column at a time? – Carl Witthoft Jul 14 '20 at 17:52

0 Answers0