Search code examples
rloopsrastercropmask

New rasters from crop of rasters by one polygon in loop R


From 19 climatic rasters, I try to crop only the raster area in the polygon (in France). For this, I try to generate a loop that crops each rasters one by one with the polygon, like this:

# my list of raster
rlist <- list.files(path=mydir, pattern='tif$', full.names=FALSE)
# loop to generate the 19 raster
for(i in rlist) {assign(unlist(strsplit(i, "[.]"))[1], raster(i)) }

# import my polygon (France)
France <- readOGR("./QGIS/France/Shapefile/France.shp")

# crop and mask one raster by polygon France
c1 <- crop(raster1, extent(France))
c2 <- mask(c1, France)

It works, but now I'm trying to find a loop to crop and mask the 19 rasters at once, and create new raster from this crop and mask that I would have named. Any suggestions?

I don't know if it's clear, tell me if you need more info. Thanks.


Solution

  • There is no need for a loop

    library(terra)
    ff <- list.files(path=mydir, pattern='tif$', full.names=FALSE)
    x <- rast(ff)
    france <- vect("./QGIS/France/Shapefile/France.shp")
    xf <- crop(x, france, mask=TRUE)
    

    If xf has 19 layers and you want to write each to a separate file (as you indicate in the comments), you can do something like

    fout <- paste0("bio_", 1:19)
    writeRaster(xf, fout, filetype="GTiff")
    

    Also, you should never, ever, use assign. In a case like this, you could make a list instead, so that you can later iterate over its items (with for or lapply. What you were doing could be written as

    x <- lapply(ff, rast)
    y <- lapply(x, \(i) crop(i, France, mask=TRUE))
    z <- rast(y)
    

    But that is still rather clumsy