Simplest way to do parallel replicate

后端 未结 3 1051
被撕碎了的回忆
被撕碎了的回忆 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:01

    You can just use the parallel versions of lapply or sapply, instead of saying to replicate this expression n times you do the apply on 1:n and instead of giving an expression, you wrap that expression in a function that ignores the argument sent to it.

    possibly something like:

    #create cluster
    library(parallel)
    cl <- makeCluster(detectCores()-1)  
    # get library support needed to run the code
    clusterEvalQ(cl,library(MASS))
    # put objects in place that might be needed for the code
    myData <- data.frame(x=1:10, y=rnorm(10))
    clusterExport(cl,c("myData"))
    # Set a different seed on each member of the cluster (just in case)
    clusterSetRNGStream(cl)
    #... then parallel replicate...
    parSapply(cl, 1:10000, function(i,...) { x <- rnorm(10); mean(x)/sd(x) } )
    #stop the cluster
    stopCluster(cl)
    

    as the parallel equivalent of:

    replicate(10000, {x <- rnorm(10); mean(x)/sd(x) } )
    

提交回复
热议问题