0

I have a stack of monthly temperature raster data and would like to calculate the global spatial mean per area using the terra package in R to obtain a monthly time series.

I tried terra::app and terra::mean but they both give me a raster with a temporal average per gridcell, not the spatial average. terra::extract might be another solution but I can't seem to get it to work, since I am interested in the global mean.

This feels like a very basic thing to do so apologies if it is obvious. Any tips appreciated.

Thanks

1 Answer 1

1

You are after the function terra::global. Make sure to use na.rm=TRUE else wise, if there are NA' present the result will be NA. If the SpatRaster object is multi-layer, results will be returned for each layer.

library(terra)
r <- rast(ncols=100, nrows=100)
  r[] <- runif(ncell(r))
    r[c(50,100,1000)] <- NA

global(r, "mean")
global(r, "mean", na.rm=TRUE)

If you need to return the specific value to use as a scalar a given band can be indexed. Otherwise the returned object is a data.frame and a function that is expecting a numeric value will fail.

class(global(r, "mean", na.rm=TRUE))
global(r, "mean", na.rm=TRUE)[,1] 
1
  • Worked like a charm, thank you! I was also wondering if there is an elegant way to store the time object with it? I can of course add it to the data frame using terra::time but it feels a bit hacky to me.
    – LuleSa
    Oct 4, 2023 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.