You can do (using a slightly modified example to make it easier to see what happens):
library(terra)
s <- rast(ncols=10, nrows=10)
s <- init(s, 1:10)
v <- c(1, 10, 100, 1000)
a <- app(s, function(x, aa){ sapply(aa, function(i) 2 * i/x) }, aa=v)
a
#class : SpatRaster
#dimensions : 10, 10, 3 (nrow, ncol, nlyr)
#resolution : 36, 18 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : lyr.1, lyr.2, lyr.3
#min values : 0.2, 2.0, 20.0
#max values : 2, 20, 200
With terra
version 1.3-17 (currently the development version), you can now also do:
b <- 2 * v/s
to get the same results. The layers of a SpatRaster are recycled when doing arithmetic with a vector that is longer than the number of layers.
With a SpatRasterDataSet you can do something like the below. It is important to test fun
outside of lapp
to see if the number of values returned, and their order, make sense.
fun = function(i, j) {
v <- c(1, 10, 100, 1000)
f <- i + j
f <- rep(f, each=length(v))
matrix(v / f, ncol=length(v), byrow=TRUE)
}
srd <- sds(list(i = s, j = s/10))
r <- lapp(srd, fun = fun)