Open In App

TryCatch with parLapply (Parallel package) in R

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In R, tryCatch is used to handles errors and warnings at run time. In combination with parLapply from the parallel package, it makes it possible to execute code in parallel, making it more efficient while taking care of possible errors.

  • tryCatch: A function for error and warning handling during execution.
  • parLapply: Runs a function over a list in parallel, increasing execution speed.

Syntax:

tryCatch({
}, error = function(e) {
}, warning = function(w) {
})

Parallel Function Execution with Error Handling

Here is an illustration of how to process a list of inputs in parallel using tryCatch and parLapply.

R
library(parallel)

# Define function with tryCatch
my_function <- function(x) {
  tryCatch({
    result <- sqrt(x)
    return(result)
  }, error = function(e) {
    return(NA)
  }, warning = function(w) {
    return(NA)
  })
}

# Create cluster
cl <- makeCluster(2)

inputs <- list(1, 2, 3, 4, 5)

# Apply function in parallel
results <- parLapply(cl, inputs, my_function)

stopCluster(cl)
print(results)

Output:

[[1]]
[1] 1

[[2]]
[1] 1.414214

[[3]]
[1] 1.732051

[[4]]
[1] 2

[[5]]
[1] 2.236068

Explanation: This example declares my_function with tryCatch to catch errors and warnings. parLapply applies this function in parallel to each element of the input, and errors (e.g., computing square roots of negative numbers) are caught and processed by returning NA.

Handling Median Calculation with Invalid Input

R
library(parallel)

compute_median <- function(x) {
  tryCatch({
    # Check if the input is numeric before calculating the median
    if (is.numeric(x)) {
      return(median(x))
    } else {
      stop("Error: Non-numeric data")
    }
  }, error = function(e) {
    return(NA)  
  })
}

cl <- makeCluster(2)

# Define the list containing vectors of numbers (with one non-numeric vector)
lis <- list(c(11, 12, 13), c(14, 15, 16), c("a", "b", "c"), c(17, 18, 19))

# Apply the function in parallel
medians <- parLapply(cl, lis, compute_median)

stopCluster(cl)
print(medians)

Output:

[[1]]
[1] 12

[[2]]
[1] 15

[[3]]
[1] "b"

[[4]]
[1] 18

Explanation: The compute_median function here computes the median of a vector. If the vector has non-numeric values (such as c("a", "b", "c")), tryCatch catches the error and returns NA for that element.

Replacing Missing Values in a DataFrame

Let's say we want to substitute the missing values in each column of a data frame with the mean value for that column. TryCatch will be used to manage any potential errors, and an error message will be returned. Here is an illustration of how to do it:
 

R
df <- data.frame(x = c(11, 12, 13, NA, 15), y = c(NA, 12, 13, 14, 15))

replace_missing_values <- function(x) {
  tryCatch({
    return(ifelse(is.na(x), mean(x, na.rm = TRUE), x))
  }, error = function(e) {
    return("Error: Unable to replace missing values")
  })
}

# Apply function to each column
df_imputed <- as.data.frame(lapply(df, replace_missing_values))
print(df_imputed)

Output:

      x    y
1 11.00 13.5
2 12.00 12.0
3 13.00 13.0
4 12.75 14.0
5 15.00 15.0

Managing File Read Failures

R
file_paths <- c("file1.txt", "file2.txt", "file3.txt")

# Function to read file
r_f_c <- function(file_path) {
  tryCatch({
    return(readLines(file_path))
  }, error = function(e) {
    return(paste("Error: Unable to read file", file_path))
  })
}

# Apply function to file paths
file_contents <- lapply(file_paths, r_f_c)
print(file_contents)

Output:

[[1]]
[1] "Error: Unable to read file file1.txt"

[[2]]
[1] "Error: Unable to read file file2.txt"

[[3]]
[1] "Error: Unable to read file file3.txt"

Explanation: This is an example of error handling for file read. If a file cannot be read or does not exist, tryCatch traps the error and returns a message rather than terminating the execution.

Handling Division-by-Zero Error

Consider dividing a vector of numbers by a constant value, but the constant value is zero. We want to use "tryCatch" to manage the division by zero error and return an error message. Here is an illustration of how to do it.

R
num <- c(1, 2, 3, 4, 5)

# Function to divide by a variable
div_b_var <- function(x, var) {
  if (var == 0) {
    stop("Error: Not able to divide by 0")
  } else {
    return(x / var)
  }
}

# Apply function in parallel
cl <- makeCluster(2)
result <- tryCatch({
  parLapply(cl, num, div_b_var, var = 0)
}, error = function(e) {
  message("Error: Not able to divide by 0")
})

# Stop cluster
stopCluster(cl)

# Print result
if (inherits(result, "try-error")) {
  message(result)
} else {
  print(result)
}

Output:

Error: Not able to divide by 0
NULL

Explanation: This demonstrates how tryCatch deals with a division-by-zero error when attempting to divide the numbers vector by 0. The error is trapped, and a message is printed rather than the code crashing.


Article Tags :

Similar Reads