首页 > 解决方案 > 并行化应用于 parRapply

问题描述

我的数据集是:

ll <- matrix(c(5, 6, 60, 60), ncol=2)

我使用库“sp”中的函数spDistsN1通过apply获得距离矩阵:

apply(ll, 1, function(x) spDistsN1(as.matrix(ll), x, longlat = T))

但我想通过并行化来做到这一点,因此:

library(parallel)
ncore <- detectCores()
cl <- makeCluster(ncore)
clusterEvalQ(cl = cl, expr = c(library(sp)))
parRapply(cl = cl, x = ll, FUN =  function(x) spDistsN1(as.matrix(ll), x, 
longlat = T))

它显示以下错误:

checkForRemoteErrors(val) 中的错误:4 个节点产生错误;第一个错误:找不到对象“将”

我如何解决它?

标签: rparallel-processingapplysp

解决方案


使用并行的更简单的替代方法parApply()是使用parRapply()future.apply(免责声明:我是作者),因为全局变量会自动导出 - 无需担心等。只需像使用它一样使用它,例如future_apply()parallel::clusterExport()apply()

library(sp)
library(future.apply)
plan(multiprocess)  ## parallelize on local machine

ll <- matrix(c(5, 6, 60, 60), ncol = 2)

## Sequentially
y0 <-        apply(ll, 1, function(x) A(ll, x, longlat = TRUE))
print(y0)
#          [,1]     [,2]
# [1,]  0.00000 55.79918
# [2,] 55.79918  0.00000

## In parallel
y1 <- future_apply(ll, 1, function(x) spDistsN1(ll, x, longlat = TRUE))
print(y1)
#          [,1]     [,2]
# [1,]  0.00000 55.79918
# [2,] 55.79918  0.00000

print(identical(y1, y0))
# [1] TRUE

您可能还会发现博文 future.apply - Parallelize Any Base R Apply Function很有帮助。


推荐阅读