A lean, terra-based replacement for the crop/mask/reproject that reproducible::prepInputs() performed internally (via postProcessTo()), without the caching, options, and download machinery. Intended to run after a layer has been fetched and read, e.g. with workflowtools::drive_download_once() + workflowtools::archive_extract_once() + terra::vect().

prep_vector(
  x,
  studyArea,
  crs = terra::crs(studyArea),
  mask = TRUE,
  makeValid = TRUE,
  buffer = 0.1
)

Arguments

x

A SpatVector, or a file path or data source readable by terra::vect().

studyArea

A SpatVector (or a source readable by terra::vect()) defining the area of interest, to which x is clipped. May be in any CRS.

crs

Target coordinate reference system, in any form accepted by terra::project(). Defaults to the CRS of studyArea.

mask

Logical. If TRUE (the default), clip x to the studyArea polygon geometry; if FALSE, crop to its (buffered) extent only.

makeValid

Logical. If TRUE (the default), repair geometry with terra::makeValid() before and after each geometry operation.

buffer

Numeric. Fraction of the larger study-area extent dimension by which to expand the source-CRS pre-crop extent (default 0.1); 0 disables the buffer. The pre-crop extent is always clamped to x's own extent.

Value

A SpatVector reprojected to crs and clipped to studyArea, retaining only the attributes of x.

Details

The processing mirrors what prepInputs() does, in this order:

  1. repair x (and studyArea) topology with terra::makeValid();

  2. pre-crop in the source CRS – project the (small) studyArea into x's CRS, take a buffered extent, and crop x to it, so large or complex layers are reduced before the costly reprojection (rather than reprojecting the whole source);

  3. reproject the reduced layer to crs;

  4. clip precisely to the studyArea polygon (when mask = TRUE).

Geometry validity is repaired after every crop/mask/reproject step, since each of those operations can introduce invalid geometries.

Examples

studyArea <- terra::vect("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")
terra::crs(studyArea) <- "EPSG:3857"
x <- terra::vect("POLYGON ((8 4, 12 4, 12 6, 8 6, 8 4))")
terra::crs(x) <- "EPSG:3857"
prep_vector(x, studyArea)
#> class       : SpatVector
#> geometry    : polygons
#> dimensions  : 1, 0  (geometries, attributes)
#> extent      : 8, 10, 4, 6  (xmin, xmax, ymin, ymax)
#> coord. ref. : WGS 84 / Pseudo-Mercator (EPSG:3857)