Learn R Programming

thisutils (version 0.3.1)

parallelize_fun: Parallelize a function

Description

Parallelize a function

Usage

parallelize_fun(
  x,
  fun,
  cores = 1,
  export_fun = NULL,
  clean_result = FALSE,
  throw_error = TRUE,
  timestamp_format = paste0("[", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "] "),
  verbose = TRUE
)

Value

A list of computed results. If clean_result = FALSE, failed results are included as error objects. If clean_result = TRUE, only successful results are returned.

Arguments

x

A vector or list to apply over.

fun

The function to be applied to each element.

cores

The number of cores to use for parallelization with foreach::foreach. Default is 1.

export_fun

The functions to export the function to workers.

clean_result

Whether to remove failed results from output. If FALSE, failed results are kept as error objects. Default is FALSE.

throw_error

Whether to print detailed error information for failed results. Default is TRUE.

timestamp_format

Format string for timestamp display. Default is "%Y-%m-%d %H:%M:%S".

verbose

Whether to print the message. Default is TRUE.

Examples

Run this code
parallelize_fun(1:3, function(x) {
  Sys.sleep(0.2)
  x^2
})

parallelize_fun(list(1, 2, 3), function(x) {
  Sys.sleep(0.2)
  x^2
}, cores = 2)

# Examples with error handling
parallelize_fun(1:5, function(x) {
  if (x == 3) stop("Error on element 3")
  x^2
}, clean_result = FALSE)

parallelize_fun(1:5, function(x) {
  if (x == 3) stop("Error on element 3")
  x^2
}, clean_result = TRUE)

# Control error printing
parallelize_fun(1:5, function(x) {
  if (x == 2) stop("Error on element 3")
  if (x == 4) stop("Error on element 4")
  x^2
})

parallelize_fun(1:5, function(x) {
  if (x == 3) stop("Error on element 3")
  x^2
}, throw_error = FALSE)

Run the code above in your browser using DataLab