Simplest way to do parallel replicate

后端 未结 3 1055
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 16:33

I am fond of the parallel package in R and how easy and intuitive it is to do parallel versions of apply, sapply, etc.

Is the

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 17:08

    Using clusterEvalQ as a model, I think I would implement a parallel replicate as:

    parReplicate <- function(cl, n, expr, simplify=TRUE, USE.NAMES=TRUE)
      parSapply(cl, integer(n), function(i, ex) eval(ex, envir=.GlobalEnv),
                substitute(expr), simplify=simplify, USE.NAMES=USE.NAMES)
    

    The arguments simplify and USE.NAMES are compatible with sapply rather than replicate, but they make it a better wrapper around parSapply in my opinion.

    Here's an example derived from the replicate man page:

    library(parallel)
    cl <- makePSOCKcluster(3)
    hist(parReplicate(cl, 100, mean(rexp(10))))
    

提交回复
热议问题