Clip a raster layer by a spatial polygon
Source:R/Spat_ClipRasterByPolygon.R
ClipRasterByPolygon.Rd
This function clips a raster layer using a specified spatial polygon, effectively masking the raster outside the polygon area. The resulting clipped raster retains the original raster's properties and values within the polygon's bounds.
Value
A RasterLayer object representing the portion of the input raster that falls within the specified polygon. The returned raster contains the same data as the original within the polygon's bounds but is masked (set to NA) outside of it.
Examples
library(sp)
library(raster)
library(rworldmap)
#> ### Welcome to rworldmap ###
#> For a short introduction type : vignette('rworldmap')
# Example Polygon
SPDF <- getMap(resolution = "low") %>%
subset(NAME == "Germany")
# Example RasterLayer
r <- raster::raster(nrow = 1e3, ncol = 1e3, crs = proj4string(SPDF))
r[] <- seq_len(length(r))
plot(r)
plot(SPDF, add = TRUE)
# ----------------------------------
SPDF_DE <- ClipRasterByPolygon(r, SPDF)
plot(raster::extent(SPDF_DE), axes = FALSE, xlab = "", ylab = "")
plot(SPDF_DE, add = TRUE)
plot(SPDF, add = TRUE)