# foreach parallel loop comes from "foreach" package # we also need to load doParallel package to define a parallel backend library(parallel) library(foreach) library(doParallel) # Check how many cores are requested by the job ( ncores <- as.numeric( Sys.getenv("NSLOTS") ) ) # If code is executed interactively, set the number of cores manually if ( is.na(ncores) ) ncores <- 1 # Define a sample dataset set.seed(42) df <- as.data.frame( matrix(sample(1:100, 100000000, replace=TRUE), nrow=100000) ) # Create a cluster from CPU cores and define a parallel backend cl <- makeCluster(ncores) # from library(parallel) registerDoParallel(cl) # from library(doParallel) # Execute a loop in parallel res <- foreach(xc=df, .combine='c') %dopar% { # compute sum of each vector (column in the input data frame) sum(xc) } # Stop the cluster stopCluster(cl)