Learn R Programming

reproducible (version 3.2.1)

postProcess: Generic function to post process objects

Description

[Stable]

The method for GIS objects (terra Spat* & sf classes) will crop, reproject, and mask, in that order. This is a wrapper for cropTo(), fixErrorsIn(), projectTo(), maskTo() and writeTo(), with a required amount of data manipulation between these calls so that the crs match.

Usage

postProcess(x, ...)

# S3 method for list postProcess(x, ...)

# S3 method for default postProcess(x, ...)

Value

A GIS file (e.g., RasterLayer, SpatRaster etc.) that has been appropriately cropped, reprojected, masked, depending on the inputs.

Arguments

x

A GIS object of postProcessing, e.g., Spat* or sf*. This can be provided as a rlang::quosure or a normal R object.

...

Additional arguments passed to methods. For spatialClasses, these are: cropTo(), fixErrorsIn(), projectTo(), maskTo(), determineFilename(), and writeTo(). Each of these may also pass ... into other functions, like writeTo(). This might include potentially important arguments like datatype, format. Also passed to terra::project, with likely important arguments such as method = "bilinear". See details.

Post processing sequence

If the rasterToMatch or studyArea are passed, then the following sequence will occur:

  1. Fix errors fixErrorsIn(). Currently only errors fixed are for SpatialPolygons using buffer(..., width = 0).

  2. Crop using cropTo()

  3. Project using projectTo()

  4. Mask using maskTo()

  5. Determine file name determineFilename()

  6. Write that file name to disk, optionally writeTo()

NOTE: checksumming does not occur during the post-processing stage, as there are no file downloads. To achieve fast results, wrap prepInputs with Cache

Backwards compatibility with <code>rasterToMatch</code> and/or <code>studyArea</code> arguments

For backwards compatibility, postProcess will continue to allow passing rasterToMatch and/or studyArea arguments. Depending on which of these are passed, different things will happen to the targetFile located at filename1.

See Use cases section in postProcessTo() for post processing behaviour with the new from and to arguments.

If targetFile is a raster (Raster*, or SpatRaster) object:

rasterToMatchstudyAreaBoth
extentYesYesrasterToMatch
resolutionYesNorasterToMatch
projectionYesNo*rasterToMatch*
alignmentYesNorasterToMatch
maskNo**YesstudyArea**

*Can be overridden with useSAcrs.

**Will mask with NAs from rasterToMatch if maskWithRTM.

If targetFile is a vector (Spatial*, sf or SpatVector) object:

rasterToMatchstudyAreaBoth
extentYesYesrasterToMatch
resolutionNANANA
projectionYesNo*rasterToMatch*
alignmentNANANA
maskNoYesstudyArea

*Can be overridden with useSAcrs

See Also

prepInputs

Examples

Run this code
if (requireNamespace("terra", quietly = TRUE) &&
    requireNamespace("withr", quietly = TRUE)) {
  library(reproducible)
  withr::local_dir(withr::local_tempdir())
  withr::local_options(reproducible.inputPaths = NULL)
  # od <- setwd(tempdir2())
  # download a (spatial) file from remote url (which often is an archive) load into R
  # need 3 files for this example; 1 from remote, 2 local
  dPath <- file.path(tempdir2())
  # the `CRAN` tag tracks terra's current CRAN release; `master` moves and is flakier
  remoteTifUrl <- "https://github.com/rspatial/terra/raw/CRAN/inst/ex/elev.tif"

  localFileLuxSm <- system.file("ex/luxSmall/luxSmall.shp", package = "reproducible")
  localFileLux <- system.file("ex/lux.shp", package = "terra")

  # 1 step for each layer
  # 1st step -- get study area
  studyArea <- prepInputs(localFileLuxSm, fun = "terra::vect") # default is sf::st_read

  # Requires internet -- gated on NOT_CRAN so CRAN's machines are never asked to
  #   reach a third-party server, and wrapped in try() for when the server is down
  if (identical(Sys.getenv("NOT_CRAN"), "true")) {
    # 2nd step: make the input data layer like the studyArea map
    elevForStudy <- try(prepInputs(url = remoteTifUrl, to = studyArea, res = 250,
                                   destinationPath = dPath, useCache = FALSE))
  }

  ## The single call above is equivalent to all the steps below, which must be known and
  ##   repeated for every layer. Left commented out: it is an explanation, not a test.
  ##
  ## dir.create(dPath, recursive = TRUE, showWarnings = FALSE)
  ## file.copy(localFileLuxSm, file.path(dPath, basename(localFileLuxSm)))
  ## studyArea2 <- terra::vect(localFileLuxSm)
  ## if (!all(terra::is.valid(studyArea2))) studyArea2 <- terra::makeValid(studyArea2)
  ## tf <- tempfile(fileext = ".tif")
  ## download.file(url = remoteTifUrl, destfile = tf, mode = "wb", quiet = TRUE)
  ## Checksums(dPath, write = TRUE, files = tf)
  ## elevOrig <- terra::rast(tf)
  ## studyAreaCrs <- terra::crs(studyArea)
  ## # Build an explicit target raster (same CRS as studyArea, res = 250) and project to
  ## # it. Avoids the recursive `terra::project(x, char_crs, res = N)` shorthand that
  ## # recent terra (~1.9) regressed with `[write] unknown option(s): xscale,yscale`.
  ## elevTarget <- terra::project(terra::rast(elevOrig), studyAreaCrs)
  ## elevTarget <- terra::rast(terra::ext(elevTarget),
  ##                           crs = terra::crs(elevTarget),
  ##                           resolution = 250)
  ## elevForStudy2 <- terra::project(elevOrig, elevTarget) |>
  ##   terra::mask(studyArea2) |>
  ##   terra::crop(studyArea2)
  ##
  ## isTRUE(all.equal(elevForStudy, elevForStudy2)) # TRUE!

  # sf class
  if (requireNamespace("sf", quietly = TRUE)) {
    studyAreaSmall <- prepInputs(localFileLuxSm, fun = "sf::st_read")
    studyAreas <- list()
    studyAreas[["orig"]] <- prepInputs(localFileLux)
    studyAreas[["reprojected"]] <- projectTo(studyAreas[["orig"]], studyAreaSmall)
    studyAreas[["cropped"]] <- suppressWarnings(cropTo(studyAreas[["orig"]], studyAreaSmall))
    studyAreas[["masked"]] <- suppressWarnings(maskTo(studyAreas[["orig"]], studyAreaSmall))
  }

  # SpatVector-- note: doesn't matter what class the "to" object is, only the "from"
  studyAreas <- list()
  studyAreaSmall <- prepInputs(localFileLuxSm)
  studyAreas[["orig"]] <- prepInputs(localFileLux)
  studyAreas[["reprojected"]] <- projectTo(studyAreas[["orig"]], studyAreaSmall)
  studyAreas[["cropped"]] <- suppressWarnings(cropTo(studyAreas[["orig"]], studyAreaSmall))
  studyAreas[["masked"]] <- suppressWarnings(maskTo(studyAreas[["orig"]], studyAreaSmall))
  if (interactive()) {
    par(mfrow = c(2,2));
    out <- lapply(studyAreas, function(x) terra::plot(x))
  }

  withr::deferred_run()
  # setwd(od)
}

Run the code above in your browser using DataLab