在 R 中的 doParallel 并行循环中使用砖(光栅)

use of brick (raster) within doParallel parallel loop in R

我想在 R 中的并行循环内读取单独的 tif 文件。我加载了光栅包,并且 brick 在循环外工作,但在循环内尝试使用 brick 失败:

library(foreach)
library(doParallel)
library(raster)

cores=detectCores()
cl <- makeCluster(cores[1]) 
registerDoParallel(cl)

tiffile="../ESACCI-LC-L4-LC10-Map-20m-P1Y-2016-v1.0.tif"
print("step1")
bdata=brick(tiffile)

print("step2")
result<-foreach(j=1:5,.combine=rbind) %dopar% {
bpar=brick(tiffile)
}

输出:

[1] "step1"
[1] "step2"
Error in { : task 1 failed - "could not find function "brick""
Calls: %dopar% -> <Anonymous>

foreach 命令启动单独的环境,其中未加载栅格包,因此您需要在对 brick 的调用中提供完整的命名空间,如下所示...

library(foreach)
library(doParallel)
library(raster)

cores=detectCores()
cl <- makeCluster(cores[1]) 
registerDoParallel(cl)

tiffile="../ESACCI-LC-L4-LC10-Map-20m-P1Y-2016-v1.0.tif"
print("step1")
bdata=brick(tiffile)

print("step2")
result<-foreach(j=1:5,.combine=rbind) %dopar% {
    bpar=raster::brick(tiffile)
}