# Install and load the required packages
install.packages("foreach")
install.packages("doParallel")
library(foreach)
library(doParallel)
# Set the number of cores to be used
num_cores <- 4
cl <- makeCluster(num_cores)
registerDoParallel(cl)
# Create a list or vector to iterate over
my_list <- list(a = 1, b = 2, c = 3, d = 4)
# Define the function to be applied to each element of the list
my_function <- function(x) {
# Your code here
# ...
return(result)
}
# Use foreach to apply the function to each element in parallel
results <- foreach(item = my_list, .combine = c) %dopar% {
my_function(item)
}
# Stop the parallel processing
stopCluster(cl)
# View the results
print(results)