rparallel-processingmclapply

Unable to parallelize a function with multiple arguments in R


I tried to parallelize a simple function which adds two numbers and prints the result in R using mclapply in the library parallel. This is my code :

library(doParallel)
t = list(list(1,1),list(2,2),list(3,3))
f <- function (a,b){
    print(a + b)
}
mclapply(t,f)

But it returns the error :

Warning message in mclapply(t, f):
“all scheduled cores encountered errors in user code”
[[1]]
[1] "Error in print(a + b) : argument \"b\" is missing, with no default\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in print(a + b): argument "b" is missing, with no default>

[[2]]
[1] "Error in print(a + b) : argument \"b\" is missing, with no default\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in print(a + b): argument "b" is missing, with no default>

[[3]]
[1] "Error in print(a + b) : argument \"b\" is missing, with no default\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in print(a + b): argument "b" is missing, with no default>

Can somebody please tell me what I am doing wrong here ?

I tried to search how to run a function with multiple arguments in parallel, but no answers was found.


Solution

  • mclapply is calling the function for each element of the list which itself is a list. Therefore each time you call the function you pass it a list and nothing else. You need to unpack the the list in the function:

    library(doParallel)
    t = list(list(1,1),list(2,2),list(3,3))
    f <- function (a){
      print(a[[1]] + a[[2]])
    }
    mclapply(t,f)