I have 31 rasters saved as .asc files, and a polygon shapefile saved as a .shp.
Example raster:
I want to loop through each raster, clip it (like below), and save it in a different folder.
Clipped raster
I have tried some code I found on this thread that was deemed wrong/inconclusive: Loop through clip tiff files and export to new folder
Here is what I tried:
## location of input files
ipath <- "G:/GIS/RRB_PROJECT/SDM_RASTERS/BRT_OUTPUTS/RCP26_CCSM4_2050/"
## location of output files
opath<-
"G:/GIS/RRB_PROJECT/SDM_RASTERS/BRT_OUTPUTS_CLIPPED/RCP26_CCSM4_2050/"
## location of polygon shapefile
ppath <- "G:/GIS/RRB_PROJECT"
## polygon name
pname <- "DSREACH_RCLIP"
## polygon
bound <- readOGR(ppath,pname)
## list of files
files <- list.files(ipath, pattern= '[.]asc$')
stopifnot(length(files)>0)
## loop (doesnt work)
for (i in files) {
ifile <- file.path(ipath,i)
ofile <- file.path(opath,i)
r <- mask(ifile, bound)
writeRaster(r, filename = ofile)
}
but I get this error:
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘mask’ for signature ‘"character", "SpatialPolygonsDataFrame"’
Any help is much appreciated.