| create_mask | R Documentation |
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).
create_mask(
polygon,
reference_raster = NULL,
output = tempfile(fileext = ".tif"),
apply_to = NULL,
apply_output = tempfile(fileext = ".tif")
)
polygon |
Polygon source: an |
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 |
output |
Character string: file path for the output mask GeoTIFF. Defaults to a temporary file. |
apply_to |
Character string or |
apply_output |
Character string: file path for the masked output
raster. Used only when |
The function accepts three types of polygon input:
sf objectWritten to a temporary GeoJSON file via
sf::st_write() and then rasterized.
Requires the sf package.
Passed directly to the C++ rasterizer. Any OGR-readable format is supported (shapefile, GeoJSON, GeoPackage, etc.).
SpatRaster objectUsed 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.
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.
rasterize_mask_cpp(), apply_mask_cpp()
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)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.