raveragerasterterra

Adding raster bricks based on their respective dates in R terra


I need to average two raster stacks which containing daily temperature data shifted by 2 days.

First stack times: "2020-05-01 00:00:00 UTC", "2020-05-02 00:00:00 UTC", "2020-05-03 00:00:00 UTC", "2020-05-04 00:00:00 UTC", "2020-05-05 00:00:00 UTC".

Second stack times: "2020-05-03 00:00:00 UTC", "2020-05-04 00:00:00 UTC", "2020-05-05 00:00:00 UTC", "2020-05-06 00:00:00 UTC", "2020-05-07 00:00:00 UTC",

How can I calculate the stack average such that May 3 is averaged with May 3, May 4 with May 4, etc.., and the mismatching dates are simply copied over? I am using the terra R package.


Solution

  • With vspaid's example data

    library(terra)
    r1 <- rast(ncol = 10, nrow = 10, nlyr = 5, vals = rep(1:5, each = 100))
    r2 <- rast(ncol = 10, nrow = 10, nlyr = 5, vals = rep(6:10, each = 100))
    time(r1) <- seq(as.Date("2000-01-01"), length.out = 5, by = 1)
    time(r2) <- seq(as.Date("2000-01-03"), length.out = 5, by = 1)
    

    You can do

    tapp(c(r1, r2), "day", mean)
    
    #class       : SpatRaster 
    #size        : 10, 10, 7  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
    #source(s)   : memory
    #names       : d_2000.01.01, d_2000.01.02, d_2000.01.03, d_2000.01.04, d_2000.01.05, d_2000.01.06, ... 
    #min values  :            1,            2,          4.5,          5.5,          6.5,            9, ... 
    #max values  :            1,            2,          4.5,          5.5,          6.5,            9, ... 
    #time (days) : 2000-01-01 to 2000-01-07 (7 steps) 
    

    This solution is equivalent to:

    x <- c(r1, r2)
    y <- tapp(x, time(x), mean)
    time(y) <- as.Date(names(y), "X%Y.%d.%m")
    

    For these example data, the approach below also works

    x <- rast(r1, nlyr=2, vals=NA)
    mean(c(r1, x), c(x, r2), na.rm=TRUE)