Update to a previous post: cutting multiple rasters with a multi-polygon shapefile
[This article was first published on R Code – Geekcologist, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
A little while ago I posted here a function which was enormously useful for me (and I thought it might be for others to). At the time, I needed to cut many rasters by a multipolygon shapefile and create rasters with the result of this operation.
However, recently, I provided some advice to a fellow Geekcologist and realized that the function needed to be slightly tweaked.
Here is the new code (the ID field in the shapefile attribute table must be “id”).
crop_save <- function(origin_folder, pattern, destination_folder, name_sub_folder, crop_areas, name_crop_areas){
file_list <- list.files(path = origin_folder, pattern)
#Create folder
dir.create(paste0(destination_folder,"/",name_sub_folder))
how_many_areas <- nrow(crop_areas)
#Create raster stack
raster_stack <- stack()
#File paths
paths1 <- paste0(origin_folder,file_list)
#Load rasters to stack
for(i in 1:length(file_list)){
raster_stack <- stack(raster_stack, raster(paths1[i]))
}
names_list <- eval(parse(text=name_crop_areas))
numbers <- 1:length(names_list)
names_list <- paste0(as.character(numbers),"_polygon_", names_list)
polyRR_list <- list()
for(x in 1: nrow(crop_areas)){
pol1 <- assign(names_list[x],crop_areas[x,])
polyRR_list[[x]] <- pol1
}
for(j in 1:nlayers(raster_stack)){
dir.create(paste0(destination_folder,"/",name_sub_folder, "/", names(raster_stack)[j]))
for(k in 1:length(polyRR_list)){
a <- crop(raster_stack[[j]], polyRR_list[[k]])
a <- mask(a,polyRR_list[[k]], filename = paste0(destination_folder,"/",
name_sub_folder, "/", names(raster_stack)[j], "/",polyRR_list[[k]]$id, ".tif"))
}
}
}
To leave a comment for the author, please follow the link and comment on their blog: R Code – Geekcologist.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.