Iteratively crop and mask several rasters with a shapefile

I am having 20 raster layers and 1 shapefile. I would like to:

  1. crop and mask each raster iteratively (i.e., first crop and mask the first raster, then the second and so on)

  2. save each cropped raster with the same name as its original into a subfolder of the working directory.

I can do this for every raster (manually, one-by-one) but I would like to automate the process. My raster layers do not have the same extent, that's why I want to crop and mask each one by one (also they are large in size (mb)). Here is the code for doing this in a one-by-one manner:

library(terra)

setwd("path")

r1 = rast("path/a.tif")
r2 = rast("path/b.tif")
poly <- vect("path/poly.shp")

r1 <- crop(r1, 
           poly, 
           mask = T)

r2 <- crop(r2, 
           poly, 
           mask = T)

dir.create(file.path(getwd(), 'clip'), recursive = T)

writeRaster(r1, "path/clip/r1.tif")
writeRaster(r2, "path/clip/r2.tif")

From here you can download a small subset the data.

This should work. I changed the folder names and am using projects so you will need to change that.

library(terra)
library(tidyverse)
library(glue)

r1 <- rast("folder/a.tif")
r2 <- rast("folder/b.tif")
poly <- vect("folder/poly.shp")

rasters <- c("r1", "r2") %>% 
  set_names()

map(rasters, ~crop(get(.x), poly, mask = T) %>% 
      writeRaster(glue("clip/{.x}.tif"))
    )

## output ------------------
# $r1
# class       : SpatRaster 
# dimensions  : 201, 108, 1  (nrow, ncol, nlyr)
# resolution  : 100, 100  (x, y)
# extent      : 583400, 594200, 1005800, 1025900  (xmin, xmax, ymin, ymax)
# coord. ref. : WGS 84 / Maharashtra (EPSG:7767) 
# source      : r1.tif 
# name        :         a 
# min value   :  46.93765 
# max value   : 549.67786 
# 
# $r2
# class       : SpatRaster 
# dimensions  : 202, 107, 1  (nrow, ncol, nlyr)
# resolution  : 100, 100  (x, y)
# extent      : 583419.3, 594119.3, 1005764, 1025964  (xmin, xmax, ymin, ymax)
# coord. ref. : WGS 84 / Maharashtra (EPSG:7767) 
# source      : r2.tif 
# name        :         b 
# min value   :  50.11665 
# max value   : 554.80945 
1 Like

Just to mention that I had to create the subfolder in order for your code to run without an error. Maybe I should have mentioned that in the post that I would like the folder to be created inside the code but still, your code runs perfectly fine.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.