Skip to content

Instantly share code, notes, and snippets.

@benfasoli
Last active January 11, 2018 03:02
Show Gist options
  • Save benfasoli/d5233dba23a94a96cbe763034ec918b2 to your computer and use it in GitHub Desktop.
Save benfasoli/d5233dba23a94a96cbe763034ec918b2 to your computer and use it in GitHub Desktop.
Crop raster to complex polygon
library(raster)
library(rgdal)
# Load footprint from file into rasterBrick object
path_to_footprint_nc <- './footprint.nc'
footprint <- brick(path_to_footprint_nc)
# Sum values per-cell into raster object
r_all <- sum(footprint)
# Read in counties shapefile
shape <- readOGR(dsn = 'Counties', layer = 'Counties')
# Grab the SLCo polygon from the counties shapefile
slco <- spTransform(subset(shape, NAME == 'SALT LAKE'), CRS('+proj=longlat'))
# Replace values outside of SLCo with NA
r_slco <- mask(r, slco)
# Plot pre-crop and post-crop for validation
op <- par(mfrow = c(1, 2))
plot(r_all, main = 'Full Domain')
plot(r_slco, main = 'SLCo')
par(op)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment