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

我与影子孤独终老i 提交于 2019-12-25 01:56:13

问题


I would like to calculate the maximum length of consecutive days above a threshold t given a raster stack s as shown below:

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

Here is my current function.

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

I have also set a parameter q for export as advised in the cluster {raster} function

q <- 0

I expect a raster layer as an output but instead the error below pops up.

[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

What could be the problem?


回答1:


First, if you use random values in your example data, please also set the random seed so it's reproducible.

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))

As to your question, the only thing you need is a simple function that can be passed into calc to obtain the desired results:

cd <- function(x,t){

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

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

  return(max(z,0))

}

This function uses rle, or run length encoding, to calculate the number of consecutive runs in a vector. In this case I'm looking for the maximum number of consecutive 1s, which come from multiplying TRUE values (value is above threshold t) with 1.

In the end you want to return the maximum run of a value 1, with 0 being a fallback in case there's no occurrence (sidenote: 1 indicates a single, non-consecutive occurence).

Finally, cd can be passed into calc, in this case using a threshold of 40:

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



来源:https://stackoverflow.com/questions/56255507/calculate-maximum-length-of-consecutive-days-above-a-certain-threshold-in-a-rast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!