It is easier to do this with "terra" (the replacement of "raster"),
Example data
library(terra)
s1 <- rast(system.file("ex/logo.tif", package="terra"))
s2 <- sqrt(s1)
Solutions to get the "parallel" mean with two SpatRasters:
mean(s1, s2)
#class : SpatRaster
#dimensions : 77, 101, 3 (nrow, ncol, nlyr)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#coord. ref. : Cartesian (Meter)
#source(s) : memory
#names : red, green, blue
#min values : 0.0000, 0.0000, 0.0000
#max values : 135.4844, 135.4844, 135.4844
Or like this
app(sds(s1, s2), mean)
If you have many files (SpatRasters) you can do:
f <- system.file("ex/logo.tif", package="terra")
ff <- rep(f, 5)
s <- sds(ff)
app(s, mean)
# or
x <- lapply(ff, rast)
do.call(mean, x)
# or
x <- lapply(ff, rast)
app(sds(x), mean)
To subset each SpatRaster before the computations, you can do
x <- lapply(ff, \(f) rast(f)[[1:2]])
do.call(mean, x)
Or (but this is currently broken)
s <- sds(ff)
s <- s[, 1:2,drop=FALSE]
app(s, mean)
You can, of course, also subset the output with [[1:2]]
Note that to get the mean of all layers you could do this instead
mean(c(s1, s2))
# or
app(c(s1, s2), mean)