You can use sapply
in combination with lapp
({terra}
package, since it's faster than {raster}
):
sapply(1:25, function(X) lapp(c(x[[X]],y), function(x,y){x*y}))
Por parallelization, you can use cores
argument:
library(parallel)
n = detectCores()
sapply(1:25, function(X) lapp(c(x[[X]],y), function(x,y){x*y}, cores = n))
You can even export each result:
sapply(1:25, function(X) lapp(c(x[[X]],y), function(x,y){x*y}, filename = paste0('path/to/file', X, '.tif')))
Reproducible example:
library(terra)
set.seed(123)
x = rast()
y = rast()
x = rast(sapply(1:25, function(X){setValues(x,rnorm(ncell(x)))}))
y = setValues(y,rnorm(ncell(y)))
print(x)
# class : SpatRaster
# dimensions : 180, 360, 25 (nrow, ncol, nlyr)
# resolution : 1, 1 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84
# source(s) : memory
# names : lyr.1, lyr.1, lyr.1, lyr.1, lyr.1, lyr.1, ...
# min values : -4.129135, -4.382098, -4.289319, -4.23503, -4.132421, -4.351687, ...
# max values : 4.322815, 4.206090, 4.124220, 4.52151, 4.599884, 4.759086, ...
print(y)
# class : SpatRaster
# dimensions : 180, 360, 1 (nrow, ncol, nlyr)
# resolution : 1, 1 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84
# source(s) : memory
# name : lyr.1
# min value : -3.985896
# max value : 4.165254
rast(sapply(1:25, function(X) lapp(c(x[[X]],y), function(x,y){x*y})))
# class : SpatRaster
# dimensions : 180, 360, 25 (nrow, ncol, nlyr)
# resolution : 1, 1 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84
# source(s) : memory
# names : lyr1, lyr1, lyr1, lyr1, lyr1, lyr1, ...
# min values : -7.865725, -12.337091, -9.967996, -8.919808, -9.330696, -9.985127, ...
# max values : 7.787720, 9.870736, 11.646272, 9.325943, 10.125534, 10.062626, ...
prod(c(ndvi,urban), na.rm=TRUE)
however the rasters need to be SpatRasters objects read or coerced usingterra::rast