PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

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

 July 27, 2022     crop, loops, r, raster     No comments   

Issue

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]) 
}


Answered By - Robert Hijmans
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing