简体   繁体   中英

New rasters from crop of rasters by one polygon in loop R

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.

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)

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(xf, fout, filetype="GTiff")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM