title: How to crop multiple rasters to the same extent using a for loop in R?
body: <p>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.</p>
  <p>Code so far:</p>
  <pre><code>raster_files &lt;- list.files(here::here(&quot;data&quot;, &quot;s2_rasters&quot;)) #dir with 4 rasters 
  raster_paths &lt;- paste0(here::here(&quot;data&quot;, &quot;s2_rasters&quot;, raster_files))
  
  wp_shp &lt;- readOGR(here::here(&quot;data&quot;, &quot;wp_boundary.shp&quot;))
  e &lt;- extent(wp_shp)
  
  n &lt;- length(raster_paths)
  
  for (i in 1:n) {
    m &lt;- raster_paths[i]
    crop(x = m, y = e) 
  }
  </code></pre>
  <p>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.).</p>
  <p>Here's an example I did for a single crop that worked fine.</p>
  <pre><code>extent &lt;- extent(802331.9, 802503.7, 9884986, 9885133)
  
  ras_crop &lt;- stack(here::here(&quot;data&quot;, &quot;s2_rasters&quot;, &quot;sample_raster.tif&quot;)) %&gt;% 
    crop(extent) %&gt;%
    writeRaster(filename=file.path(here::here(&quot;data&quot;, &quot;s2_rasters&quot;), &quot;raster1_crop.tif&quot;))
  </code></pre>