如何在 r 的不同集群中 运行 一个函数 x 次?

How to run a function x times in different clusters in r?

我有这个命令: replicate(10^4, binom_ttest(100, 0.5)) %>% {sum(.<0.05)}/20000

binom_ttest 是我创建的函数,returns 2x p.value 1 用于 binom 检验,1 用于 t 检验

由于这是一个很长的计算,我想问一下如何将它分配到 2 个集群? 我知道 parLapply 有可能,但这不起作用: parLapply(makeCluster(2), 1:10000, binom_ttest(100, 0.5))

这是 parallel 的示例测试 运行。我建议尝试使用简单函数的干 运行,然后将其扩展为更复杂的示例。

附带说明一下,您使用的每个数据集都必须可供所有集群使用,因此必须像下面示例中的 simpl() 一样导出。

library(parallel)

cl <- makeCluster(getOption("cl.cores", 2))

cl
# socket cluster with 2 nodes on host ‘localhost’

simpl <- function(x)diag(x)

clusterExport(cl, varlist=("simpl"))

parLapply( cl, 1:5, function(x) simpl(x) )
#[[1]]
#     [,1]
#[1,]    1
#
#[[2]]
#     [,1] [,2]
#[1,]    1    0
#[2,]    0    1
#
#... etc
#
#[[5]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    0    0    0
#[2,]    0    1    0    0    0
#[3,]    0    0    1    0    0
#[4,]    0    0    0    1    0
#[5,]    0    0    0    0    1

stopCluster(cl)

future.apply package provides future_replicate(),这是replicate()的并行实现;

library(future.apply)
plan(multisession, workers = 2)

y <- future_replicate(10^4, binom_ttest(100, 0.5))

它确保使用正确的并行随机数生成 (RNG),这在进行排列测试、自举等时至关重要。

这是一个方法。
忘记导出函数给worker,为了代码可复现,最好设置伪RNG。

library(parallel)

binom_ttest <- function(n, p) {   
  x <- sample(0:1, n, replace = TRUE, prob = c(1-p, p))   
  xsum <- sum(x==1)    
  p_binom <- binom.test(xsum, n, 0.5)[["p.value"]]   
  p_ttest <- t.test(x, mu=0.5)[["p.value"]]   
  c(p_binom, p_ttest) 
}

cl <- makeCluster(2)
clusterExport(cl, "binom_ttest")
clusterSetRNGStream(cl = cl, 2021)
res <- parSapply(cl, 1:10000, FUN = function(i) binom_ttest(100, 0.5))
stopCluster(cl)

rowMeans(res < 0.05)
#[1] 0.0347 0.0571