I have a Rasterstack X of 92 layers (all days of June, July, August). Which maps the difference between the maximum temperature on that day and a threshold which I have defined.
class : RasterStack
dimensions : 201, 464, 93264, 92 (nrow, ncol, ncell, nlayers)
resolution : 0.25, 0.25 (x, y)
extent : -40.5, 75.5, 25.25, 75.5 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
To give you an idea of what these layers look like I have plotted the first layer at the bottom of this post: the difference T_max - T_threshold for June 1st. What I want to do now is to take the sum over the layers, but only where X > 0 for at least 3 consecutive days. The result would be just 1 RasterLayer.
I have created the following function to do this. The script does exactly what I want it to when I run it on a vector of numbers.
total <- stack()
sum <- stack()
consec <- stack()
test <- function(X) {
for (day in 1:nlayers(X)) {
if (X[[day]] > 0) {
consec = consec + 1
sum = sum + X[[day]]
}
else if (consec >= 3) { total = total + sum
consec = 0
sum = 0}
else {consec = 0
sum = 0 }
}
return(total)
}
calc(x = X, fun = test)
This gives me the following error:
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
cannot use this function
I think I understand why it gives me this error: calc()
usually runs a function on all layers, but I want it to run on different layers for different pixel values.
I have been breaking my head over this for a long time. Does someone know how I can best solve this?
calc
andoverlay
function, internally return a vector of values associated with each cell. For example, you are using
nlayers(X)` and a double bracket for indexing. It would be1:length(X)
andX[day]
. I would create a dummy vector eg.,y<-runif(92,0,10)
to test your function. I would also suggest looking at thewhich
andrle
functions to optimize your code.