Clipping raster using shapefile in R, but keeping the geometry of the shapefile
One option is to use raster::mask()
library(maptools) ## For wrld_simpllibrary(raster)## Example SpatialPolygonsDataFramedata(wrld_simpl)SPDF <- subset(wrld_simpl, NAME=="Brazil")## Example RasterLayerr <- raster(nrow=1e3, ncol=1e3, crs=proj4string(SPDF))r[] <- 1:length(r)## crop and maskr2 <- crop(r, extent(SPDF))r3 <- mask(r2, SPDF)## Check that it workedplot(r3)plot(SPDF, add=TRUE, lwd=2)
For simple geometries (i.g. box), the coordinates of the extent can be place directly:
e <- as(extent(c(xmin= -16, xmax= -7.25, ymin= 4, ymax= 12.75)), 'SpatialPolygons')crs(e) <- "+proj=longlat +datum=WGS84 +no_defs"r <- crop(my_raster, e)
Source: https://gis.stackexchange.com/questions/229356/crop-a-raster-file-in-r/389376#389376