Converts a polygon source to a binary raster mask aligned to a reference
raster, and optionally applies that mask to an input raster (replacing
pixels outside all polygons with NA).
Arguments
- polygon
Polygon source: an
sfobject, a character file path to an OGR-readable vector source, or aterra::SpatRasterused directly as a binary mask.- reference_raster
Character string: path to a GDAL-readable raster used to set the spatial reference (extent, resolution, CRS) of the output mask. Ignored when
polygonis aSpatRaster.- output
Character string: file path for the output mask GeoTIFF. Defaults to a temporary file.
- apply_to
Character string or
NULL: if supplied, path to a GDAL-readable raster to which the mask will be applied. Pixels outside all polygons are set toNAin the result.- apply_output
Character string: file path for the masked output raster. Used only when
apply_tois notNULL. Defaults to a temporary file.
Value
When apply_to is NULL, returns the path to the binary mask
GeoTIFF invisibly. When apply_to is provided, returns the path to the
masked output raster invisibly.
Details
The function accepts three types of polygon input:
sfobjectWritten to a temporary GeoJSON file via
sf::st_write()and then rasterized. Requires the sf package.- Character file path
Passed directly to the C++ rasterizer. Any OGR-readable format is supported (shapefile, GeoJSON, GeoPackage, etc.).
SpatRasterobjectUsed directly as a pre-made mask raster. Must already be binary (0/1) and aligned to
reference_raster. Requires the terra package.
All GDAL-dependent operations skip gracefully (returning NULL invisibly
with a message) when the package was built without GDAL support.
Examples
# \donttest{
if (has_gdal()) {
# Requires GDAL support at build time.
ref <- system.file("extdata", "tiny.tif", package = "xbioclim")
poly <- tempfile(fileext = ".geojson")
writeLines(
paste0(
'{"type":"FeatureCollection","features":[{"type":"Feature",',
'"geometry":{"type":"Polygon",',
'"coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]},',
'"properties":{}}]}'
),
poly
)
mask_path <- create_mask(poly, ref)
}
#> Warning: /tmp/RtmpRzND6Y/file31e664680927.tif: No such file or directory (GDAL error 4)
# }