catch error reading file and report filename in r

To catch an error when reading a file in R, you can use a tryCatch() function. This function allows you to intercept and handle errors that occur during evaluation of R expressions.

To report the filename of the file that caused an error, you can include the filename in the error message using paste() or paste0() functions.

Here's an example code snippet that demonstrates this approach:

main.r
filename <- "example_file.csv"

# Wrap file reading in tryCatch block
tryCatch(
  {
    data <- read.csv(filename)
  },
  
  # Define error handling function
  error = function(e) {
    message(paste0("Error reading ", filename, ":\n", e$message))
  }
)
254 chars
14 lines

In this code, we try to read a file "example_file.csv" using read.csv() function. If an error occurs during file reading, the error handling function is called with the error message stored in the "e" parameter. We use paste0() function to concatenate the filename with the error message and print it using message() function.

Note that tryCatch() function allows you to define separate error handling functions for different types of errors, such as warning, message, or condition errors. You can customize the error handling behavior based on your specific needs.

gistlibby LogSnag