0

I have 31 rasters saved as .asc files, and a polygon shapefile saved as a .shp.

Example raster:

Example of raster

I want to loop through each raster, clip it (like below), and save it in a different folder.

Clipped raster

Example of 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.

Community
  • 1
  • 1
  • It's tough to help without a reproducible example. I can see however that the error message is saying the `mask` function cannot cope with a character string as its first argument. The function is expecting some sort of Raster object so you need to read the file using the `raster` function first. – Andrew Chisholm Jan 04 '19 at 15:51
  • Per awchisholm's suggestion, I was able to get this for loop to work by changing this line: r <- mask(ifile, bound) to this: r <- mask(raster(ifile), bound) – Fully Aquatic Jan 04 '19 at 19:17

0 Answers0