我需要将 rasterbrick 聚合为每月值。通常,使用 zApply
包中的 raster
函数会很容易。但是,我有一个很大的光栅,这需要很长时间。
所以基本上,我想知道使用 parallel
或 clusterR
之类的库是否容易做到这一点,但我不知道如何并行化这个过程
# create a random raster stack
library(raster)
lay <- stack()
for (i in 1:365){
print(i)
ras <- matrix(rnorm(500, mean = 21, sd = rnorm(21, 12, 4)))
ras <- raster(ras)
lay <- addLayer(lay, ras)
}
dats <- seq(as.Date('2000-01-01'), length.out = nlayers(lay), by = 'days')
lay <- setZ(lay, dats)
monthlies <- zApply(lay, by = format(dats,"%m"), fun = 'mean') # aggregate from daily to monthly.
谢谢!
最佳答案
使用 foraech 和 doParallel 包
您可以使用 foreach
和 doParallel
来实现您的结果。
您将需要:
detectCores()
DoParallel
registerDoParallel(numCores)
以与您的 CPU 内核一起工作foreach
循环。 您的代码将如下所示:
library(foreach)
library(doParallel)
library(raster)
lay <- stack()
## Loading required package: iterators
numCores <- detectCores()
registerDoParallel(numCores) # use multicore, set to the number of our cores
lay <- foreach (i=1:365, .init = lay, .combine = addLayer , .packages = "raster") %dopar% {
print(i)
ras <- matrix(rnorm(500, mean = 21, sd = rnorm(21, 12, 4)))
ras <- raster(ras)
}
dats <- seq(as.Date('2000-01-01'), length.out = nlayers(lay), by = 'days')
lay <- setZ(lay, dats)
monthlies <- zApply(lay, by = format(dats,"%m"), fun = 'mean') # aggregate from daily to monthly
# When you're done, clean up the cluster
stopImplicitCluster()
测量速度改进
您可以使用
System.time()
测试速度提升。这些是我的结果:#Time with a standard for loop
system.time({
for (i in 1:365){
print(i)
ras <- matrix(rnorm(500, mean = 21, sd = rnorm(21, 12, 4)))
ras <- raster(ras)
lay <- addLayer(lay, ras)
}
})
user system elapsed
66.29 0.09 67.15
#Testing foreach loop time
system.time({
lay <- foreach (i=1:365, .init = lay, .combine = addLayer , .packages = "raster") %dopar% {
print(i)
ras <- matrix(rnorm(500, mean = 21, sd = rnorm(21, 12, 4)))
ras <- raster(ras)
}
})
user system elapsed
21.72 0.09 25.58
正如我们所看到的,使用这种方法可以有效地提高速度。
希望这可以帮助。
关于r: zApply 在并行计算中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59765510/