问题
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 1
s, 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