[英]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.我有 4 个要裁剪到相同程度的栅格。 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.在这个脚本的未来迭代中,我将有超过 4 个,所以我正在尝试编写一个循环,将目录中的所有栅格裁剪到相同的程度。 The rasters are downloaded Sentinel-2 products containing at least 4 bands that have been converted into GeoTIFFs using the sen2r() library.栅格是下载的 Sentinel-2 产品,其中包含至少 4 个波段,这些波段已使用 sen2r() 库转换为 GeoTIFF。 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"))
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])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.