计算栅格堆栈中超过特定​​阈值的连续天数的最大长度

Calculate maximum length of consecutive days above a certain threshold in a raster stack

我想计算给定栅格堆栈s超过阈值t的连续天数的最大长度,如下所示:

library(raster)

set.seed(112)

x1 <- raster(nrows=10, ncols=10)
x2=x3=x4=x5=x6=x1
x1[]= runif(ncell(x1))
x2[]= runif(ncell(x1))
x3[]= runif(ncell(x1))
x4[]= runif(ncell(x1))
x5[]= runif(ncell(x1))
x6[]= runif(ncell(x1))
s=stack(x1,x2,x3,x4,x5,x6)*56

这是我当前的函数。

fun <- function(x,t){
  y <- rle((x > t)*1)
  z <- y$lengths[y$values==1]
  return(max(z,0))
}

我还按照 cluster {raster} 函数

中的建议设置了导出参数 q
q <- 0

我希望栅格图层作为输出,但弹出以下错误。

[1] "cannot use this function"
attr(,"class")
[1] "snow-try-error" "try-error"     
Error in clusterR(s, calc, args = list(fun = fun), export = "q") : 
  cluster error

可能是什么问题?

首先,如果您在示例数据中使用随机值,请同时设置随机种子以使其可重现。

library(raster)

set.seed(42)

x1 <- raster(nrows=10, ncols=10)

s <- do.call(stack,lapply(1:6,function(x) setValues(x1,runif(ncell(x1)))*56))

关于你的问题,你唯一需要的是一个简单的函数,可以将其传递给 calc 以获得所需的结果:

cd <- function(x,t){

  y <- rle((x > t)*1)

  z <- y$lengths[y$values==1]

  return(max(z,0))

}

此函数使用rle或运行长度编码,计算向量中连续运行的个数。在这种情况下,我正在寻找连续 1 的最大数量,它来自将 TRUE 值(值高于阈值 t)乘以 1.

最后你想要 return 值 1 的最大值 运行,如果没有出现 0 作为后备(旁注:1 表示单个, non-consecutive 次)。

最后,cd可以传入calc,本例使用阈值40:

plot(calc(s,function(x) cd(x,40)))