Search code examples
rdesign-patternsrasterqgis

Read specific raster files and create a mean raster in R


I am desesperate, because my problem seems very simple, but I cannot find out how to manage it.

Aim:

  1. I would like to read 1 to 4 raster files from a folder. The names of the one that I need are listed in a list as character.
  2. After having opened the files, I would like to create a new raster corresponding to the mean of the files.

I can manage it on QGIS, but I need to automatize hte process, as I have a lot of individuals!

1) It should work with list.files(pattern = ) but as the names are in a list, I do not know how to do.

Ex: for the first individual, I have to read 2 files named 2018-12-27_sic.tif and 2018-12-27_sic_con.tif

I tried to read with readGDAL , open.GDAL it didn't work

thanks a lot for your valuable help


Solution

  • I would use the stack and calc functions from the raster package. The function stack creates a stack of rasters, all with the same resolution and extent, and makes it easy to do operations like take the mean of every cell. So:

    library(raster)
    
    fs <- list.files(pattern='tif$')
    
    rasterstack <- stack(fs)
    
    rastermean <- calc(rasterstack, fun=mean)
    

    Note, if your rasters are not the same resolution, you will have to use the resample function, and if they are not the same extent, you will have to use crop. Typing in ?resample and ?crop in RStudio will show you instructions for using those functions.