From 19 climatic rasters, I try to crop only the raster area in the polygon (in France). For this, I try to generate a loop that crops each rasters one by one with the polygon, like this:
# my list of raster
rlist <- list.files(path=mydir, pattern='tif$', full.names=FALSE)
# loop to generate the 19 raster
for(i in rlist) {assign(unlist(strsplit(i, "[.]"))[1], raster(i)) }
# import my polygon (France)
France <- readOGR("./QGIS/France/Shapefile/France.shp")
# crop and mask one raster by polygon France
c1 <- crop(raster1, extent(France))
c2 <- mask(c1, France)
It works, but now I'm trying to find a loop to crop and mask the 19 rasters at once, and create new raster from this crop and mask that I would have named. Any suggestions?
I don't know if it's clear, tell me if you need more info. Thanks.
CodePudding user response:
There is no need for a loop
library(terra)
ff <- list.files(path=mydir, pattern='tif$', full.names=FALSE)
x <- rast(ff)
france <- vect("./QGIS/France/Shapefile/France.shp")
xf <- crop(x, france, mask=TRUE)
If xf
has 19 layers and you want to write each to a separate file (as you indicate in the comments), you can do something like
fout <- paste0("bio_", 1:19)
writeRaster(x, fout)
Also, you should never, ever, use assign
. In a case like this, you could make a list instead, so that you can later iterate over its items (with for
or lapply
. What you were doing could be written as
x <- lapply(ff, rast)
y <- lapply(x, \(i) crop(i, France, mask=TRUE))
z <- rast(y)
But that is still rather clumsy
CodePudding user response:
I recommend you to switch to terra
. It's from the same author than raster
library but it's faster:
library(terra)
files <- list.files(path=mydir, pattern='tif$', full.names=TRUE)
v <- vect("./QGIS/France/Shapefile/France.shp")
l <- list()
for(i in seq_along(files)){
rtemp <- rast(files[i])
l[[i]] <- crop(rtemp, v, mask=TRUE)
}
s <- rast(l)