如何在R语言for循环中捕获错误并写入日志文件?
Solution Using
tryCatch() in R Got it, let's fix this with a working implementation that hits all your requirements. The tryCatch() function is definitely the right tool here—you just need to structure it to capture errors, build your log row, and append to the file correctly. Here's a complete, tested example:
# Define log file path log_file <- "TextLogFile.txt" # Initialize log file with headers if it doesn't exist if (!file.exists(log_file)) { log_headers <- data.frame( Run = integer(), ID = character(), TimeStamp = POSIXct(), Runtime = numeric(), Error = character(), stringsAsFactors = FALSE ) # Write headers as tab-separated text (adjust sep to "," for CSV if needed) write.table(log_headers, log_file, sep = "\t", row.names = FALSE, quote = FALSE) } # Initialize empty in-memory log data frame temp_log <- data.frame() # Loop from 1 to 5 for (i in 1:5) { # Record start time for runtime calculation start_time <- Sys.time() # Set default error message error_msg <- "No Error" # Wrap your iteration logic in tryCatch to capture errors tryCatch({ # ---------------------- # Replace this with your actual code # Example 1: No errors (uncomment this, comment Example 2) iteration_result <- i * 2 # Example 2: Trigger error at i=3 (uncomment this, comment Example 1) # if (i == 3) { tp0 <- tp0 + 1 } else { iteration_result <- i * 2 } # ---------------------- }, error = function(e) { # Capture and store the actual error message error_msg <<- conditionMessage(e) }) # Calculate runtime in seconds end_time <- Sys.time() runtime <- as.numeric(difftime(end_time, start_time, units = "secs")) # Build a single log row log_row <- data.frame( Run = i, ID = paste0("Iteration_", i), # Customize ID as needed TimeStamp = start_time, Runtime = runtime, Error = error_msg, stringsAsFactors = FALSE ) # Append row to in-memory temp_log temp_log <- rbind(temp_log, log_row) # Append row to the text log file (skip column names since we wrote headers once) write.table(log_row, log_file, sep = "\t", row.names = FALSE, col.names = FALSE, append = TRUE, quote = FALSE) } # Optional: View the in-memory log print(temp_log)
Key Details Explained
- Log File Initialization: We check if the log file exists first—if not, we write the column headers to ensure the log is structured correctly.
tryCatch()Usage: The error handler uses<<-to assign the error message to theerror_msgvariable outside the handler's scope (using<-would only modify it locally, which won't work).- Log Row Fields: Captures all the required data:
Run: Iteration numberID: Customizable unique identifier for each iterationTimeStamp: Start time of the iterationRuntime: Duration of the iteration in seconds (adjustunitsindifftime()for minutes/hours if needed)Error: "No Error" if successful, or the actual error message if something breaks
- Appending to File: Uses
append=TRUEandcol.names=FALSEto add each new row without re-writing headers.
Sample Outputs
Example 1: No Errors
The TextLogFile.txt will look like this (tab-separated):
Run ID TimeStamp Runtime Error 1 Iteration_1 2024-05-20 15:45:00 0.001 No Error 2 Iteration_2 2024-05-20 15:45:00 0.000 No Error 3 Iteration_3 2024-05-20 15:45:00 0.000 No Error 4 Iteration_4 2024-05-20 15:45:00 0.001 No Error 5 Iteration_5 2024-05-20 15:45:00 0.000 No Error
Example 2: Error at i=3
The log file will include the actual error message:
Run ID TimeStamp Runtime Error 1 Iteration_1 2024-05-20 15:50:00 0.001 No Error 2 Iteration_2 2024-05-20 15:50:00 0.000 No Error 3 Iteration_3 2024-05-20 15:50:00 0.002 Error in tp0 : object 'tp0' not found 4 Iteration_4 2024-05-20 15:50:00 0.000 No Error 5 Iteration_5 2024-05-20 15:50:00 0.001 No Error
内容的提问来源于stack exchange,提问作者Som B
相关产品推荐
相关产品推荐

