Here is an example that raster library provides for using clusterR and overlay functions:
library(raster)
beginCluster()
r <- raster()
r[] <- 1:ncell(r)
s <- stack(r, r*2, r*3)
f2 <- function(d,e,f) (d + e) / (f * param)
param <- 122
ov <- clusterR(s, overlay, args=list(fun=f2), export='param')
I want to know how to run that function if I have multiple raster stacks:
s <- stack(r, r*2, r*3)
s2 <- stack(r*2, r*3, r*4)
s3 <- stack(r*3, r*4, r*5)
I want something like this (d,e,f
in function f2
are each layer in s, s2
and s3
):
ov <- clusterR(s,s2,s3, overlay, args=list(fun=f2), export='param')
First I would create a dummy raster layer in your stack holding the param
value. Thus, the operations can be vectorized:
p <- 122
rp <- r
rp[] <- p
s <- stack(s, rp)
s2 <- stack(s2, rp)
s3 <- stack(s3, rp)
Then you change your function like this:
f2 <- function(x) (x[[1]] + x[[2]]) / (x[[3]] * x[[4]])
Thus, the layers of the individual stack x
are referred to correctly. The 4th layer is the param
value (here p
)
Then you create a list of layer stacks:
stackList <- list(s, s2, s3)
then you lapply
the clusterR
function.
ov <- lapply(stackList, function(x){clusterR(x, fun = f2, progress = "text")})
ov
will then be a list of your overlaid layers.