Suppose I have a function f()
and a vector d
f <- function(x) dexp(x, 2)
d <- runif(10, 1, 5)
Now I want to perform a for loop like
dnew <- numeric(length(d))
for (i in seq_along(dnew)){
dnew[i] <- f(d[i])
}
. How can I do this in parallel?
foreach
package, others findfuture
to be great, too.foreach
used correctly does not speed it up, then (1) start-up costs do not offset parallel execution; (2) you did it wrong or it could be done better; or (3) something else we don't know. In general, for parallelization to work well, the calculation time has to be significantly more than the start-up cost (fork R if appropriate, load libraries, transfer data, etc). If you include yourforeach
code, perhaps somebody adept at that package can help improve its performance.