Skip to contents

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).

Usage

create_mask(
  polygon,
  reference_raster = NULL,
  output = tempfile(fileext = ".tif"),
  apply_to = NULL,
  apply_output = tempfile(fileext = ".tif")
)

Arguments

polygon

Polygon source: an sf object, a character file path to an OGR-readable vector source, or a terra::SpatRaster used 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 polygon is a SpatRaster.

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 to NA in the result.

apply_output

Character string: file path for the masked output raster. Used only when apply_to is not NULL. 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:

sf object

Written 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.).

SpatRaster object

Used 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)
# }