Sunday 29 April 2018

Clipping multiple rasters by matching polygons from SPDF in R


I have about 50.000 small glacier rasters (rectangular shape) that need to be clipped to the glacier's extent. I have the glacier polygons stored in a large SpatialPolygonsDataFrame.


I want to use parallel computing or else it would take forever, I think. For previous tasks I've successfully used the mcmapplyfunction, but I am open for other approaches.


My (admittedly rudimentary) code so far is:


filenames <- list.files("/.../RGI60-13_reproj/", pattern="*.tif", full.names=F)
filelocations <- list.files("/.../RGI60-13_reproj/", pattern="*.tif", full.names=T)
glaciers <- readOGR("/.../13_rgi60_CentralAsia.shp",verbose=TRUE)


fun_clip <- function(filelocations, filenames, glaciers){
r <- raster(filelocations)
r <- crop(r,glaciers) # here I need to clarify the corresponding shp in the SPDF
writeRaster(r, paste0("/.../RGI60-13_crop/",filenames))
}

mcmapply(fun_proj, filelocations, filenames, mc.cores = 50)

How can I give the crop-function the right iterative arguments? filelocationis of the same length as glaciers, so in a for-loopI would use something like r <- crop(r,glaciers[i]), but how do I pass the iteration in my kind of function? What would be the way to introduce the i, so to speak?





No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...