Search code examples
rmeantiffr-raster

How to use grp function to calculate mean of same months raster files of different years


I have monthly raster data (.tiff) from 2008 to 2020. Files nomenclature is as follows:

index_200801
index_200802
..
..
..
index_202005

I want to calculate mean of same months of different years.

I am using the following code in R:

rast <- list.files((path="F:/Test/", pattern=".tiff$", full.names=TRUE) 
stk = stack(rast)
grp = rep(1:12, rep(??,12)

But I do not understand how to group the files.

Could anyone please help me in this and in exporting the plot.

In output, there should be 12 images, one for each month i.e., Jan (having mean of Jan 2008, Jan 2009...Jan 2020)..similarly for Feb...Dec.


Solution

  • You can do

    ff <- list.files((path="F:/Test/", pattern=".tiff$", full.names=TRUE) 
    grp <- substr(basename(ff), 11, 12)
    
    library(terra)
    x <- rast(ff)
    y <- tapp(x, grp, mean)