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.
postProcess(x, ...)
# S3 method for class 'list'
postProcess(x, ...)
# Default S3 method
postProcess(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.
A GIS file (e.g., RasterLayer, SpatRaster etc.) that has been
appropriately cropped, reprojected, masked, depending on the inputs.
If the rasterToMatch or studyArea are passed, then
the following sequence will occur:
Fix errors fixErrorsIn(). Currently only errors fixed are for
SpatialPolygons using buffer(..., width = 0).
Crop using cropTo()
Project using projectTo()
Mask using maskTo()
Determine file name determineFilename()
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
rasterToMatch and/or studyArea argumentsFor 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.
targetFile is a raster (Raster*, or SpatRaster) object:rasterToMatch | studyArea | Both | |
extent | Yes | Yes | rasterToMatch |
resolution | Yes | No | rasterToMatch |
projection | Yes | No* | rasterToMatch* |
alignment | Yes | No | rasterToMatch |
mask | No** | Yes | studyArea** |
*Can be overridden with useSAcrs.
**Will mask with NAs from rasterToMatch if maskWithRTM.
prepInputs
if (requireNamespace("terra", quietly = TRUE) && requireNamespace("sf", quietly = TRUE)) {
library(reproducible)
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())
remoteTifUrl <- "https://github.com/rspatial/terra/raw/master/inst/ex/elev.tif"
localFileLuxSm <- system.file("ex/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
# 2nd step: make the input data layer like the studyArea map
# Test only relevant if connected to internet -- so using try just in case
elevForStudy <- try(prepInputs(url = remoteTifUrl, to = studyArea, res = 250,
destinationPath = dPath, useCache = FALSE))
# Alternate way, one step at a time. Must know each of these steps, and perform for each layer
# \donttest{
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)
elevForStudy2 <- terra::project(elevOrig, studyAreaCrs, res = 250) |>
terra::mask(studyArea2) |>
terra::crop(studyArea2)
isTRUE(all.equal(elevForStudy, elevForStudy2)) # TRUE!
# }
# sf class
studyAreaSmall <- prepInputs(localFileLuxSm)
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()
studyAreas[["orig"]] <- prepInputs(localFileLux, fun = "terra::vect")
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))
}
setwd(od)
}
#> Running `prepInputs`
#> Running `preProcess`
#> Preparing: /home/runner/work/_temp/Library/reproducible/ex/luxSmall.shp
#> alsoExtract is unspecified; assuming that all files must be extracted
#> Running `process` (i.e., loading file into R)
#> targetFile located at:
#> /home/runner/work/_temp/Library/reproducible/ex/luxSmall.shp
#> Loading object into R
#> Running `prepInputs`
#> Running `preProcess`
#> targetFile was not supplied; guessed and will try
#> /tmp/RtmpgIZ9bl/reproducible/WCGeSKz1/elev.tif. If this is incorrect,
#> please supply targetFile
#> Preparing: elev.tif
#> ...downloading...
#> Downloading https://github.com/rspatial/terra/raw/master/inst/ex/elev.tif ...
#> Hardlinked version of file(s) created:
#> ... no copy/copies made.
#> alsoExtract is unspecified; assuming that all files must be extracted
#> Appending checksums to CHECKSUMS.txt. If you see this message repeatedly, you
#> can specify targetFile (and optionally alsoExtract) so it knows what to
#> look for.
#> Running `process` (i.e., loading file into R)
#> targetFile located at:
#> /tmp/RtmpgIZ9bl/reproducible/WCGeSKz1/elev.tif
#> Loading object into R
#> Running `postProcessTo`
#> cropping...
#> projecting...
#>
#> projectTo is a Vector dataset, which does not define all metadata required.
#> Using the origin and extent from `ext(from)` in the projection from
#> `crs(projectTo)`.
#> If this is not correct, create a template gridded object and pass that to
#> `projectTo`...
#>
#> done! took: 0.108 secs
#> masking...
#> done! took: 0.00648 secs
#> cropping...
#> done! took: 0.025 secs
#> postProcessTo done! took: 0.221 secs
#> Running `prepInputs`
#> Running `preProcess`
#> Preparing: /home/runner/work/_temp/Library/reproducible/ex/luxSmall.shp
#> alsoExtract is unspecified; assuming that all files must be extracted
#> Using sf::st_read on shapefile because sf package is available; to force old
#> behaviour with 'raster::shapefile' use fun = 'raster::shapefile' or
#> options('reproducible.shapefileRead' = 'raster::shapefile')
#> Running `process` (i.e., loading file into R)
#> targetFile located at:
#> /home/runner/work/_temp/Library/reproducible/ex/luxSmall.shp
#> Loading object into R
#> Reading layer `luxSmall' from data source
#> `/home/runner/work/_temp/Library/reproducible/ex/luxSmall.shp'
#> using driver `ESRI Shapefile'
#> Simple feature collection with 4 features and 6 fields
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: 4522355 ymin: 11299040 xmax: 4575913 ymax: 11339850
#> Projected CRS: +proj=lcc +lat_0=0 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +ellps=GRS80 +units=m +no_defs
#> Saved! Cache file: 460d09fb19f62653.rds; fn: sf::st_read
#> Running `prepInputs`
#> Running `preProcess`
#> Preparing: /home/runner/work/_temp/Library/terra/ex/lux.shp
#> alsoExtract is unspecified; assuming that all files must be extracted
#> Using sf::st_read on shapefile because sf package is available; to force old
#> behaviour with 'raster::shapefile' use fun = 'raster::shapefile' or
#> options('reproducible.shapefileRead' = 'raster::shapefile')
#> Running `process` (i.e., loading file into R)
#> targetFile located at:
#> /home/runner/work/_temp/Library/terra/ex/lux.shp
#> Loading object into R
#> Object to retrieve (fn: sf::st_read, c6310cb748a054af.rds) ...
#> Loaded! Cached result from previous sf::st_read call
#> projecting...
#> done! took: 0.0366 secs
#> cropping...
#> done! took: 0.0302 secs
#> masking...
#> done! took: 0.045 secs
#> Running `prepInputs`
#> Running `preProcess`
#> Preparing: /home/runner/work/_temp/Library/terra/ex/lux.shp
#> alsoExtract is unspecified; assuming that all files must be extracted
#> Running `process` (i.e., loading file into R)
#> targetFile located at:
#> /home/runner/work/_temp/Library/terra/ex/lux.shp
#> Loading object into R
#> projecting...
#> done! took: 0.0325 secs
#> cropping...
#> done! took: 0.0182 secs
#> masking...
#> done! took: 0.0123 secs