Next →

Output:


      

Plots:

Debugging and Error Handling in R

Even experienced programmers encounter errors. R provides tools to find and fix problems in your code. Proper error handling ensures your scripts run smoothly even when unexpected data or situations occur.

Basic Debugging Tools

# Example of a function with a potential error
divide <- function(a, b) {
  a / b
}

# Debug the function
debug(divide)
divide(10, 0)

This function takes two numbers, a and b, and divides a by b. The issue is that dividing by zero (b = 0) will cause an error.

Handling Errors Gracefully

# Using tryCatch to handle errors
safe_divide <- function(a, b) {
  tryCatch({
    result <- a / b
    result
  }, warning = function(w) {
    print("Warning occurred")
  }, error = function(e) {
    print("Error: Division by zero")
  })
}

safe_divide(10, 0)

This new function, safe_divide, uses tryCatch to run the division safely:

Here, dividing 10 by 0 would normally stop execution with an error. But with tryCatch, the function prints a friendly error message and continues running smoothly.

Debugging and error handling help make your R scripts more robust and reliable.