Search code examples
rterra

Calculating long-term mean monthly rainfall from interpolated rasters using TERRA package?


I have a SpatRaster object in R called IDW3, estimated using IDW interpolation method. I have nlyr = 240, containing 12 months x 20 years. I need to calculate the long-term mean monthly rainfall from the layers, so that I get nlyr = 12 at the end, in which each layer represents one calendar month (Jan - Dec).

I have tried using the code below, following this thread calculating long term daily means from a RASTER in R, but I want to verify the code I used.

Any thoughts and comments please?

idw3
#> class       : SpatRaster 
#> dimensions  : 723, 449, 240  (nrow, ncol, nlyr)
#> resolution  : 100, 100  (x, y)
#> extent      : 624698.7, 669598.7, 640507.8, 712807.8  (xmin, xmax, ymin, ymax)
#> coord. ref. :  
#> sources     : May 1998_masked_idw3.asc  
#>               May 1999_masked_idw3.asc  
#>               May 2000_masked_idw3.asc  
#>               ... and 237 more source(s)
#> names       :     Jan 1998,     Jan 1999,     Jan 2000,     Jan 2001,     #> Jan 2002,     Jan 2003, ... 
#> min values  :           ? ,           ? ,           ? ,           ? ,           ? ,           ? , ... 
#> max values  :           ? ,           ? ,           ? ,           ? ,           ? ,           ? , ... 

## CALCULATE THE LONGTERM MONTHLY MEANS
# get the months substring
month.ltm <- substr(my, 1,3)

# calculate the ltm using tapp funtion in terra
idw3.ltm <- tapp(idw3, month.ltm, mean)
names(idw3.ltm)
#> [1] "May" "Apr" "Aug" "Jan" "Sep" "Jul" "Jun" "Feb" "Dec"
#> [10] "Nov" "Oct" "Mar"

Solution

  • You can use tapp for that. Here are some example data

    library(terra)
    r <- rast(ncols=10, nrows=10, nlyr=24)
    values(r) <- 1:size(r)
    

    If the data are ordered by year, and then by month, you can now do

    x <- tapp(r, 1:12, mean)
    

    In other cases you may have to create another index to match the layers that need to be combined. If your data has a time-stamp, there are some shortcuts. In this case you can use index="months"

    time(r) <- as.Date("2000-01-15") + 0:23 * 30.5
    y <- tapp(r, "months", mean)