As a newbie of terra
I am finding difficult to speed up a very simple task:
I have 50 tiles of 200 x 200 x 9000 (a list of SpatRaster
).
I need to apply a mask to each tile and compute a global sum for each layer.
And repeat this for 6 different masks.
I was willing to use the function posted below, which works fine on a standard lapply
loop. As I understand it might not be worth to be parallelised since masking is involved: is that correct? Any suggestion about how to speed up this is welcome.
A sort of mwe follows:
r20 <- rast(nrow = 10, ncol = 10, nlyrs = 5, vals = 20, xmin = 0, xmax = 1, ymin = 1, ymax = 2)
r30 <- rast(nrow = 10, ncol = 10, nlyrs = 5, vals = 30, xmin = 1, xmax = 2, ymin = 0, ymax = 1)
r40 <- rast(nrow = 10, ncol = 10, nlyrs = 5, vals = 40, xmin = 1, xmax = 2, ymin = 1, ymax = 2)
rast.list <- list(r10, r20, r30, r40)
compute.layer.sum <- function(x, large.mask, code) {
terra::crop(large.mask, x) %>%
terra::match(., code) %>%
terra::mask(x,. ) %>%
global(., sum, na.rm = TRUE)
}
out <- lapply(rast.list, fun(x) compute.layer.sum(x, large.mask = large.mask, code = code))