Skip to contents

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.

Usage

ClipRasterByPolygon(raster = NULL, shape = NULL)

Arguments

raster

A RasterLayer object to be clipped. This is the raster layer that will be masked by the polygon.

shape

Extent object, or any object from which an Extent object can be extracted.

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.

Note

This function requires the 'raster' and 'sp' packages.

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)