Search code examples
rloopscropraster

How to crop multiple rasters to the same extent using a for loop in R?


I have 4 rasters I would like to crop to the same extent. In future iterations of this script I will have way more than 4, so I am trying to write a loop that will crop all rasters in a directory to the same extent. The rasters are downloaded Sentinel-2 products containing at least 4 bands that have been converted into GeoTIFFs using the sen2r() library. I've tried working with answers to similar questions posted here, but lose the bands somehow in the process, and i will need those bands to do some raster math later on.

Code so far:

raster_files <- list.files(here::here("data", "s2_rasters")) #dir with 4 rasters 
raster_paths <- paste0(here::here("data", "s2_rasters", raster_files))

wp_shp <- readOGR(here::here("data", "wp_boundary.shp"))
e <- extent(wp_shp)

n <- length(raster_paths)

for (i in 1:n) {
  m <- raster_paths[i]
  crop(x = m, y = e) 
}

EDIT: I recognize my loop doesn't make sense. I'm new to this and idk what i'm doing. Up until this point in the script I have been using the paths to the files to do stuff (build virtual rasters, apply atmospheric corrections etc.).

Here's an example I did for a single crop that worked fine.

extent <- extent(802331.9, 802503.7, 9884986, 9885133)

ras_crop <- stack(here::here("data", "s2_rasters", "sample_raster.tif")) %>% 
  crop(extent) %>%
  writeRaster(filename=file.path(here::here("data", "s2_rasters"), "raster1_crop.tif"))

Solution

  • From what I gather, you should be able to do something like this

    # input filenames
    inf <- list.files("data/s2_rasters", pattern="tif$", full.names=TRUE)
    # create output filenames and folder
    outf <- gsub("data/s2_rasters", "output", inf)
    dir.create("output", FALSE, FALSE)
    
    library(raster)
    wp_shp <- shapefile("data/wp_boundary.shp")
    e <- extent(wp_shp)
    
    for (i in 1:length(inf)) {
      b <- brick(inf[i])
      crop(b, e, filename=outf[i]) 
    }