rparallel-processingmclapply

Parallel computing using `mclapply` in R, Linux


How to convert the code below to perform parallel jobs on 5 cores?

From serial processing

nfac=length(values)
n=10
for (i in 1:5){
system(sprintf('./tools/siteLevelFLUXNET/morris/%s/prep_model_params.sh %s %s %s',i,nfac,n))
}

to Parallel processing

system(sprintf('./tools/siteLevelFLUXNET/morris/1/prep_model_params.sh %s %s %s',nfac,n)) on core 1
.
.
.
system(sprintf('./tools/siteLevelFLUXNET/morris/5/prep_model_params.sh %s %s %s',nfac,n)) on core 5

On the command terminal this can be performed using & between 2 codes, but I require nfac and n to be read from R


Solution

  • Are you looking for something like this,

    library(parallel)
    nfac=length(values)
    n=10
    # define a function 
    fun_i<-function(i)
    {
      return(system(sprintf('./tools/siteLevelFLUXNET/morris/%s/prep_model_params.sh %s %s %s',i,nfac,n)))
    }
    
    
    do.call("cbind", mclapply(X=1:5,FUN = function(X)fun_i(X),mc.cores=5))