I have a SpatRasterDataset
:
library(terra)
r = rast(system.file("ex/logo.tif", package="terra"))
s = terra::sds(r, r/2, r/3)
names(s) = letters[1:3]
It looks like:
> s
class : SpatRasterDataset
subdatasets : 3
dimensions : 77, 101 (nrow, ncol)
nlyr : 3, 3, 3
resolution : 1, 1 (x, y)
extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
coord. ref. : Cartesian (Meter)
source(s) : logo.tif, memory
names : a, b, c
I want to calculate the average data across 3 SpatRaster
in the SpatRasterDataset
. The resulting data should be a SpatRaster
with the same dimension as each SpatRaster
in the SpatRasterDataset
. This means I want to have a single SpatRaster
with dimensions : 77, 101 (nrow, ncol)
where each cell value is the average of the corresponding cells in the three subdatasets.
What I have tried so far:
> terra::app(s, mean)
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
varname : logo
names : red, green, blue
min values : 0.0000, 0.0000, 0.0000
max values : 155.8333, 155.8333, 155.8333
but not what I expected.
2
As Fernando pointed out in the comments, this works as expected (and is what you are after:
terra::app(s, mean)
To get the mean across datasets and layers you could do
rast(s) |> mean()
Simplifying:
r = rast(system.file("ex/logo.tif", package="terra"))
s3 <- c(r, r/2, r/3)
s3
class : SpatRaster
dimensions : 77, 101, 9 (nrow, ncol, nlyr)
resolution : 1, 1 (x, y)
extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
coord. ref. : Cartesian (Meter)
sources : logo.tif (3 layers)
memory (3 layers)
memory (3 layers)
colors RGB : 1, 2, 3
varnames : logo
logo
logo
names : red, green, blue, red, green, blue, ...
min values : 0, 0, 0, 0.0, 0.0, 0.0, ...
max values : 255, 255, 255, 127.5, 127.5, 127.5, ...
s3_mean <- app(s3, fun = mean, na.rm = TRUE)
s3_mean
class : SpatRaster
dimensions : 77, 101, 1 (nrow, ncol, nlyr)
resolution : 1, 1 (x, y)
extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
coord. ref. : Cartesian (Meter)
source(s) : memory
name : mean
min value : 0.0000
max value : 155.8333
plot(s3_mean)
i.e., one very small change away from terra::sds to c(.
4