【发布时间】:2020-05-03 17:04:58
【问题描述】:
我正在处理包含每日数据的气候数据文件,因此在大多数年份中,我们将 365 个栅格数据整合在一起。我想总结几天子集的文件中的值 - 比如说第 x 天到第 y 天。这可以通过 stackApply 来完成。我在下面创建了一些代码,用于生成一些栅格、创建砖块并使用 x 和 y、1 和 3 的特定值应用 stackApply。
我需要的是从两个栅格图层中获取 x 和 y。在下面的代码中,它们被称为 raster.start 和 raster.end。在第一组代码下面我有第二组可以工作但速度很慢。
library(raster)
r <- raster(nrows=100, ncols=100)
s <- stack(lapply(1:5, function(i) setValues(r, runif(ncell(r), min = -10*i, max = 10))))
raster.start <- setValues(r, sample(2, ncell(r), replace=TRUE))
raster.end <- raster.start + 3
rasterb <- brick(s)
indices <- format(as.Date(names(rasterb), format = "layer.%d"), format = "%d")
indices <- c(1,1,1,1,1)
datasum.all <- stackApply(rasterb, indices, fun = sum)
datasum.sub1 <- stackApply(rasterb[[c(1:3)]], indices, fun = sum)
这个想法是通过开始和结束栅格的行和列来对砖进行子集化并对其进行操作。这是我为此开发的代码。
raster.out <- r
for (i in 1:nrow(r)){
for (j in 1:ncol(r)){
start <- raster.start[[1]][i,j] # get the starting day
end <- raster.end[[1]][i,j] # get the ending day
raster.out[i,j] <- sum(rasterb[[start:end]][i,j])
}
}
但是,即使对于这个玩具示例,计算时间也很慢。完成大约需要 1.3 分钟。我尝试用函数替换一些代码,如下所示,但它对完成时间没有影响。非常感谢任何有关如何加快此过程的建议。
startEnd <- function(raster.start, raster.end, i,j) {
start <- raster.start[i,j] # get the starting day
end <- raster.end[i,j] # get the ending day
return(c(start,end))
}
rasterOutValue <- function(rasterb, i, j, startEnd){
return(sum(rasterb[[startEnd]][i,j]))
}
for (i in 1:nrow(raster.in1)){
for (j in 1:ncol(raster.in1)){
raster.out[i,j] <-rasterOutValue(rasterb, i, j, startEnd(raster.start, raster.end, i,j))
}
}
【问题讨论】:
-
您是否尝试过使用
*apply-function? -
我不太熟悉这些功能。我确实对堆栈溢出进行了一些研究,但没有发现任何与我想要做的相似的东西。
-
这段代码使用 stackApply 并且快了大约 3 倍 -
for (i in 1:nrow(raster.in1)){ for (j in 1:ncol(raster.in1)){ datasum.sub1 <- stackApply(rasterb[[start:end]], indices, fun = sum) } }