# \donttest{
# Define a simple task.
task <- function(x) {
# Perform computations.
Sys.sleep(0.01)
# Return the result.
mean(x)
}
# Define a matrix for the task.
x <- matrix(rnorm(100^2, mean = 10, sd = 0.5), nrow = 100, ncol = 100)
# Start an asynchronous backend.
backend <- start_backend(cores = 2, cluster_type = "psock", backend_type = "async")
# Run a task in parallel over the rows of `x`.
results <- par_apply(backend, x = x, margin = 1, fun = task)
# Run a task in parallel over the columns of `x`.
results <- par_apply(backend, x = x, margin = 2, fun = task)
# The task can also be run over all elements of `x` using `margin = c(1, 2)`.
# Improper dimensions will throw an error.
try(par_apply(backend, x = x, margin = c(1, 2, 3), fun = task))
# Disable progress tracking.
set_option("progress_track", FALSE)
# Run a task in parallel.
results <- par_apply(backend, x = x, margin = 1, fun = task)
# Enable progress tracking.
set_option("progress_track", TRUE)
# Change the progress bar options.
configure_bar(type = "modern", format = "[:bar] :percent")
# Run a task in parallel.
results <- par_apply(backend, x = x, margin = 1, fun = task)
# Stop the backend.
stop_backend(backend)
# Start a synchronous backend.
backend <- start_backend(cores = 2, cluster_type = "psock", backend_type = "sync")
# Run a task in parallel.
results <- par_apply(backend, x = x, margin = 1, fun = task)
# Disable progress tracking to remove the warning that progress is not supported.
set_option("progress_track", FALSE)
# Run a task in parallel.
results <- par_apply(backend, x = x, margin = 1, fun = task)
# Stop the backend.
stop_backend(backend)
# Run the task using the `base::lapply` (i.e., non-parallel).
results <- par_apply(NULL, x = x, margin = 1, fun = task)
# }
Run the code above in your browser using DataLab