Skip to content

Instantly share code, notes, and snippets.

@giacfalk
Last active July 20, 2022 15:17
Show Gist options
  • Save giacfalk/2d8be3aac7429e778d081283f8cda9cb to your computer and use it in GitHub Desktop.
Save giacfalk/2d8be3aac7429e778d081283f8cda9cb to your computer and use it in GitHub Desktop.
Clip a raster with sf polygon boundaries in R
if("fasterize" %in% rownames(installed.packages()) == FALSE) {install.packages("fasterize")}
if("raster" %in% rownames(installed.packages()) == FALSE) {install.packages("raster")}
clip_raster_with_sf <- function(rast, sf){
r_mask <- fasterize::fasterize(sf, rast)
r_masked <- raster::mask(rast, r_mask)
return(r_masked)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment