diff --git a/.vscode/settings.json b/.vscode/settings.json index b37744ca..4cf0f82a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,6 +4,7 @@ "CRS", "Dypsis", "Epanechnikov", + "geostatistical", "mapset", "unprojected" ] diff --git a/DESCRIPTION b/DESCRIPTION index 4ca22d3a..f57c234c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Package: fasterRaster Type: Package -Title: Faster Raster and Spatial Vector Processing Using 'GRASS GIS' -Version: 8.4.0.7 -Date: 2025-04-24 +Title: Faster Raster and Spatial Vector Processing Using 'GRASS' +Version: 8.4.1.0 +Date: 2025-06-19 Authors@R: c( person( @@ -15,12 +15,12 @@ Authors@R: ) Maintainer: Adam B. Smith Description: Processing of large-in-memory/large-on disk rasters and spatial - vectors using 'GRASS GIS' . Most functions in - the 'terra' package are recreated. Processing of medium-sized and smaller + vectors using 'GRASS' . Most functions in the + 'terra' package are recreated. Processing of medium-sized and smaller spatial objects will nearly always be faster using 'terra' or 'sf', but for large-in-memory/large-on-disk objects, 'fasterRaster' may be faster. To use most of the functions, you must have the stand-alone version (not - the 'OSGeoW4' installer version) of 'GRASS GIS' 8.0 or higher. + the 'OSGeoW4' installer version) of 'GRASS' 8.0 or higher. Depends: R (>= 4.0.0) Imports: diff --git a/NAMESPACE b/NAMESPACE index 13966d0c..5de4e956 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -9,10 +9,12 @@ export(faster) export(grassHelp) export(grassInfo) export(grassStarted) +export(installAddon) export(is.polygons) export(mow) export(pcs) export(print) +export(removeAddon) export(seqToSQL) export(st_coordinates) export(st_crs) @@ -172,12 +174,15 @@ exportMethods(minmax) exportMethods(missing.cases) exportMethods(missingCats) exportMethods(mmode) +exportMethods(multivarEnvSim) exportMethods(nacell) exportMethods(names) exportMethods(ncell) exportMethods(ncell3d) exportMethods(ncol) exportMethods(ndepth) +exportMethods(neighborhoodMatrix) +exportMethods(neighbourhoodMatrix) exportMethods(ngeom) exportMethods(nlevels) exportMethods(nlyr) @@ -194,7 +199,10 @@ exportMethods(predict) exportMethods(princomp) exportMethods(project) exportMethods(quantile) +exportMethods(rNormRast) exportMethods(rSpatialDepRast) +exportMethods(rUnifRast) +exportMethods(rWalkRast) exportMethods(range) exportMethods(rast) exportMethods(rasterize) @@ -212,10 +220,8 @@ exportMethods(replaceNAs) exportMethods(res) exportMethods(res3d) exportMethods(resample) -exportMethods(rnormRast) exportMethods(round) exportMethods(ruggedness) -exportMethods(runifRast) exportMethods(rvoronoi) exportMethods(sampleRast) exportMethods(scale) diff --git a/NEWS.md b/NEWS.md index 492a19cc..4c0fd09e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,8 +1,27 @@ +# fasterRaster 8.4.1.0 (2025-06-17) + +### Code-breaking changes +o `rnormRast()` is now `rNormRast()`. +o `runifRast()` is now `rUnifRast()`. + +### New functions and functionality +o `addons()` now reports the names of all installed addons or whether a given addon is installed. +o `installAddon()` installs an addon. +o `removeAddon()` deletes an addon. +o `centroids()` now calculates centroids of clumps in a `GRaster`. +o `multivarEnvSim()` calculates multivariate environmental similarity (MESS). +o `neighborhoodMatrix()` generates a neighborhood matrix from a polygons `GVector`. +o `rWalkRast()` creates a raster with the path of random walkers. +o `ruggedness()` now allows for calculation of the terrain ruggedness index across user-defined windows with distance-based weighting. + +### Minor fixes +o Rebranding as per **GRASS** re-brand (haromonized logo with **GRASS** April 2025 branding guidelines, "GRASS GIS" --> just "GRASS", "modules" --> "tools). + # fasterRaster 8.4.0.7 (2025-04-24) o Removed dependency on **rpanel** because its dependency on **tclk** did not work with **Docker** images. Replaced with version dependency on **omnibus**'s `screenRes()` function. # fasterRaster 8.4.0.6 (2025-03-26) -o `faster(debug = TRUE)` displays the **GRASS** command for each **GRASS** module called in a **fasterRaster** function. +o `faster(debug = TRUE)` displays the **GRASS** command for each **GRASS** tool called in a **fasterRaster** function. o `GVector[i]` works for cases with long `i`s. o Fixes to help pages. @@ -84,7 +103,7 @@ o `pca()` has been renamed `princomp()`. ### Enhanced functionality and new functions o `extract()` now automatically projects a `GVector` to match the CRS of a `GRaster` from which extraction is being made. o `grassGUI()` allows users to start the **GRASS** GUI. -o `grassHelp()` shows the manual page for a **GRASS** module. +o `grassHelp()` shows the manual page for a **GRASS** tool. o `layerIndex()` allows a `negate` argument to get the "opposite" indices of a `GRaster`. o `init()` assigns to `GRaster` cells the value of their coordinates, rows, columns, or values in a regular or chessboard-like pattern. o `regress()` replaces individual functions `intercept()`, `slope()`, `r2()`, and `tvalue()`. @@ -238,8 +257,8 @@ o `activeCat()`: Correct output when `names = TRUE`. o `expanse()`: Expanded list of units; correct assignation of units to **GRASS** unit format. o `extract()`: Extracting from a `GRaster` to a `lines` or `polygons` `GVector` works. o `fast()`: Fixed bug arising when reading vector saved by `writeRaster()`. -o + `global()`: Removed functions `"countNA"` and `"countNonNA"` from `global()` since **GRASS** module `r.report` can be mistaken. -o `nacell()` and `nonnacell()`: Correct (but slow~~~) reporting of `NA` and non-`NA` cells (workaround of error in **GRASS**'s `r.report` module). +o + `global()`: Removed functions `"countNA"` and `"countNonNA"` from `global()` since **GRASS** tool `r.report` can be mistaken. +o `nacell()` and `nonnacell()`: Correct (but slow~~~) reporting of `NA` and non-`NA` cells (workaround of error in **GRASS**'s `r.report` tool). # fasterRaster 8.3.0.7016 (2024-05-27) diff --git a/R/00e_GVector_class.r b/R/00e_GVector_class.r index 2ff4aef9..55470b72 100644 --- a/R/00e_GVector_class.r +++ b/R/00e_GVector_class.r @@ -54,7 +54,7 @@ methods::setValidity("GVector", #' #' @param table A `data.table`, `data.frame`, `GVector` with a table, or character. This can be `data.table(NULL)` or `data.frame(NULL)` if there is no table associated with the vector. If a character, this is interpreted as the name of the table in **GRASS**. #' -#' @param build Logical: If `TRUE` (default), build topology using **GRASS** module `v.build`. +#' @param build Logical: If `TRUE` (default), build topology using **GRASS** tool `v.build`. #' #' @param extensive Logical: If `TRUE`, do extensive topological checks using `v.build`. The default is `FALSE`. #' diff --git a/R/01_generics.r b/R/01_generics.r index aee8e02c..fcac7d7a 100644 --- a/R/01_generics.r +++ b/R/01_generics.r @@ -128,8 +128,8 @@ methods::setGeneric(name = "dropTable", def = function(x, ...) standardGeneric(" methods::setGeneric(name = "E", def = function(x, ...) standardGeneric("E")) # methods::setGeneric(name = "elide", def = function(x, ...) standardGeneric("elide")) -methods::setGeneric(name = "erase", package = "terra") -methods::setGeneric(name = "ext", package = "terra") +methods::setGeneric(name = "erase", package = "terra") +methods::setGeneric(name = "ext", package = "terra") methods::setGeneric(name = "extend", package = "terra") methods::setGeneric(name = "expanse", package = "terra") methods::setGeneric(name = "extract", package = "terra") @@ -199,6 +199,7 @@ methods::setGeneric(name = "merge", package = "terra") #' @importFrom terra median methods::setGeneric(name = "median", def = function(x, na.rm) standardGeneric("median")) methods::setGeneric(name = "mmode", def = function(x, ...) package = "omnibus") +methods::setGeneric(name = "multivarEnvSim", def = function(ref, proj, ...) standardGeneric("multivarEnvSim")) # "names" (in base) is primitive methods::setGeneric(name = "N", def = function(x, ...) standardGeneric("N")) @@ -206,7 +207,9 @@ methods::setGeneric(name = "ncell", package = "terra") methods::setGeneric(name = "ncell3d", def = function(x) standardGeneric("ncell3d")) methods::setGeneric(name = "ncol", def = function(x) standardGeneric("ncol")) # in base methods::setGeneric(name = "ndepth", def = function(x) standardGeneric("ndepth")) -methods::setGeneric(name = "new", package = "methods") +methods::setGeneric(name = "neighborhoodMatrix", def = function(x, ...) standardGeneric("neighborhoodMatrix")) +methods::setGeneric(name = "neighbourhoodMatrix", def = function(x, ...) standardGeneric("neighbourhoodMatrix")) +methods::setGeneric(name = "new", package = "methods") methods::setGeneric(name = "nlyr", package = "terra") methods::setGeneric(name = "nacell", def = function(x, ...) standardGeneric("nacell")) methods::setGeneric(name = "ngeom", def = function(x, ...) standardGeneric("ngeom")) @@ -238,7 +241,6 @@ methods::setGeneric(name = "rasterize", package = "terra") # from https://stackoverflow.com/questions/27886535/proper-way-to-use-cbind-rbind-with-s4-classes-in-package methods::getGeneric("rbind") methods::setGeneric(name = "rbind", signature = "...") - methods::setGeneric(name = "regress", package = "terra") methods::setGeneric(name = "remove0", def = function(x, ...) standardGeneric("remove0")) methods::setGeneric(name = "removeAngles", def = function(x, ...) standardGeneric("removeAngles")) @@ -251,10 +253,11 @@ methods::setGeneric(name = "replaceNAs", def = function(x, ...) standardGeneric( methods::setGeneric(name = "res", package = "terra") methods::setGeneric(name = "res3d", def = function(x) standardGeneric("res3d")) methods::setGeneric(name = "resample", package = "terra") -methods::setGeneric(name = "rnormRast", def = function(x, ...) standardGeneric("rnormRast")) +methods::setGeneric(name = "rNormRast", def = function(x, ...) standardGeneric("rNormRast")) methods::setGeneric(name = "ruggedness", def = function(x, ...) standardGeneric("ruggedness")) -methods::setGeneric(name = "runifRast", def = function(x, ...) standardGeneric("runifRast")) +methods::setGeneric(name = "rUnifRast", def = function(x, ...) standardGeneric("rUnifRast")) methods::setGeneric(name = "rvoronoi", def = function(x, ...) standardGeneric("rvoronoi")) +methods::setGeneric(name = "rWalkRast", def = function(x, ...) standardGeneric("rWalkRast")) methods::setGeneric(name = "S", def = function(x, ...) standardGeneric("S")) methods::setGeneric(name = "sampleRast", def = function(x, ...) standardGeneric("sampleRast")) diff --git a/R/05_GRaster_functions_by_layer.r b/R/05_GRaster_functions_by_layer.r index d55f2c8e..36f1f9e1 100644 --- a/R/05_GRaster_functions_by_layer.r +++ b/R/05_GRaster_functions_by_layer.r @@ -383,7 +383,7 @@ setMethod( ) #' Generic trigonometry function -#' @param fx Character: Name of the function in **GRASS** module `r.series`. +#' @param fx Character: Name of the function in **GRASS** tool `r.series`. #' @param x A `GRaster`. #' @noRd .genericTrig <- function(fx, x) { @@ -409,7 +409,7 @@ setMethod( } #' Generic "arc"-trigonometry function -#' @param fx Character: Name of the function in **GRASS** module `r.series`. +#' @param fx Character: Name of the function in **GRASS** tool `r.series`. #' @param x A `GRaster`. #' @noRd .genericArcTrig <- function(fx, x) { @@ -435,7 +435,7 @@ setMethod( } #' Generic function with one input (the GRaster) -#' @param fx Character: Name of the function in **GRASS** module `r.series`. +#' @param fx Character: Name of the function in **GRASS** tool `r.series`. #' @param x A `GRaster`. #' @noRd .genericRastFx <- function(fx, x) { @@ -464,7 +464,7 @@ setMethod( } #' Generic function with two inputs (GRaster and a numeric) -#' @param fx Character: Name of the function in **GRASS** module `r.series`. +#' @param fx Character: Name of the function in **GRASS** tool `r.series`. #' @param x A `GRaster`. #' @param y A numeric. #' @noRd diff --git a/R/addons.r b/R/addons.r index 9812e358..5dbb362c 100644 --- a/R/addons.r +++ b/R/addons.r @@ -1,72 +1,136 @@ #' Test if addons directory exists and if an addon is installed #' -#' @description This function tests to see if the "addons" directory specified using [faster()] actually exists, and if a particular **GRASS** `addons module is available. The `addons` folder and module must exists for methods that rely on particular **GRASS** `addons` to work. See `vignette("addons", package = "fasterRaster")`. +#' @description These functions handle **GRASS** addons, which are optional tools that can be installed. Most functions in **fasterRaster** rely on "base" **GRASS** tools (not addons), but a few do. #' -#' @param x Either `NULL` or a character specifying the name of a **GRASS** addons module. If `NULL`, the existence of the `addonsDir` (see [faster()]) will be tested. If the module name is provided, the existence of the folder and module will be tested. The "`/bin`" subfolder should not be included. +#' * `addons()`: Either lists all installed addons or verifies if one or more specific addons are installed. +#' * `installAddon()`: Installs a **GRASS** addon. An addon typically only needs installed once. You can install an addon, quit and restart **R**, attach **fasterRaster**, and any installed addons can be used without using this function again. +#' * `removeAddon()`: Delete an installed addon from your system. #' -#' @param fail Logical: If `TRUE` (default), and the addons folder is not correctly specified, the exit the function with an error. If `FALSE`, then `NULL` will be returned with a warning. +#' @param x Either `NULL` or a character specifying the name of a **GRASS** addons tool. If `NULL`, a vector of installed addons is returned. If a character vector is provided, a logical vector is returned, one per value in `x` that indicates if the respective addon is installed. #' -#' @param verbose Logical: If `TRUE` (default), display a message on success or warning (the `fail` option always displays a message). +#' @param check Logical: If `TRUE`, check to see if the addon is available (`installAddon()`)or if it is installed (`removeAddon()`). #' -#' @returns Logical. -#' -#' @seealso `vignette("addons", package = "fasterRaster")` +#' @returns `addons()`: Logical. The other functions invisibly return a logical value indicating if the operation succeeded or not. #' #' @example man/examples/ex_addons.r #' #' @aliases addons #' @rdname addons #' @export -addons <- function(x = NULL, fail = TRUE, verbose = TRUE) { +addons <- function(x = NULL) { - out <- TRUE + out <- rgrass::execGRASS("g.extension", flags = "a", intern = TRUE) + if (is.null(x)) { + out <- sort(out) + } else if (!is.null(x)) { + out <- x %in% out + names(out) <- x + } + out + +} - ao <- faster("addonsDir") - if (is.null(ao) || !file.exists(ao)) { - - msg <- paste0("The `addons` folder is incorrect. See `faster()` and `vignette(", dQuote("addons", q = FALSE), ", package = ", dQuote("fasterRaster", q = FALSE), ").") +#' @aliases installAddon +#' @rdname addons +#' @export +installAddon <- function(x, check = TRUE) { - if (fail) { - stop(msg) - } else if (!fail & verbose) { - warning(msg) + if (check) { + avails <- rgrass::execGRASS("g.extension", flags = c("l", .quiet()), intern = TRUE) + if (!(x %in% avails)) { + warning("The addon is not available on the official GRASS addon repository.") + return(invisible(FALSE)) } + } - out <- FALSE + rgrass::execGRASS("g.extension", operation = "add", extension = x, flags = .quiet()) + invisible(TRUE) + +} +#' @aliases removeAddon +#' @rdname addons +#' @export +removeAddon <- function(x, check = TRUE) { + + if (check) { + avails <- rgrass::execGRASS("g.extension", flags = c("a", .quiet())) + if (!(x %in% avails)) warning("The addon is not installed.") + return(invisible(FALSE)) } + + rgrass::execGRASS("g.extension", operation = "removeadd", extension = x, flags = c(.quiet(), "f")) + invisible(TRUE) + +} + +#' Test to see if a given addon is installed, and if not, installs it. +#' +#' @aliases .addons +#' @rdname addons +#' @keywords internal +.addons <- function(x) { + + installed <- addons(x) + if (!installed) { + installAddon(x, check = FALSE) + } + +} + + + +# # Tests if addons folder is installed +# addons <- function(xx = NULL, fail = TRUE, verbose = TRUE) { + +# out <- TRUE + +# ao <- faster("addonsDir") +# if (is.null(ao) || !file.exists(ao)) { + +# msg <- paste0("The `addons` folder is incorrect. See `faster()` and `vignette(", dQuote("addons", q = FALSE), ", package = ", dQuote("fasterRaster", q = FALSE), ").") + +# if (fail) { +# stop(msg) +# } else if (!fail & verbose) { +# warning(msg) +# } + +# out <- FALSE + +# } - if (!is.null(x)) { +# if (!is.null(x)) { - extensions <- list.files(paste0(faster("addonsDir"), "/bin")) - exts <- .fileExt(extensions) - extensions <- substr(extensions, 1L, nchar(extensions) - nchar(exts) - 1L) +# extensions <- list.files(paste0(faster("addonsDir"), "/bin")) +# exts <- .fileExt(extensions) +# extensions <- substr(extensions, 1L, nchar(extensions) - nchar(exts) - 1L) - if (!(x %in% extensions)) { +# if (!(x %in% extensions)) { - msg <- paste0("The addon extension `", x, "` cannot be found. See `vignette(", dQuote("addons", q = FALSE), ", package = ", dQuote("fasterRaster", q = FALSE), ").") - if (fail) { - stop(msg) - } else if (!fail & verbose) { - warning(msg) - } +# msg <- paste0("The addon extension `", x, "` cannot be found. See `vignette(", dQuote("addons", q = FALSE), ", package = ", dQuote("fasterRaster", q = FALSE), ").") +# if (fail) { +# stop(msg) +# } else if (!fail & verbose) { +# warning(msg) +# } - out <- FALSE +# out <- FALSE - } - } +# } +# } - if (verbose) { - if (is.null(x)) { - omnibus::say("Addons directory exists.") - } else { - if (out) { - omnibus::say("Addon `", x, "` is installed.") - } else { - omnibus::say("Addon `", x, "` cannot be found.") - } - } - } - invisible(out) +# if (verbose) { +# if (is.null(x)) { +# omnibus::say("Addons directory exists.") +# } else { +# if (out) { +# omnibus::say("Addon `", x, "` is installed.") +# } else { +# omnibus::say("Addon `", x, "` cannot be found.") +# } +# } +# } +# invisible(out) -} +# } diff --git a/R/app.r b/R/app.r index 30eb0ca8..2edaaf57 100644 --- a/R/app.r +++ b/R/app.r @@ -24,7 +24,7 @@ #' * It must use typical arithmetic operators like `+`, `-`, `*`, `/` and/or functions that can be seen using `appFuns(TRUE)`. #' * The [names()] of the rasters do not match any of the functions in the `appFuns(TRUE)` table. Note that `x` and `y` are forbidden names :( #' -#' The help page for **GRASS** module `r.mapcalc` will be especially helpful. You can see this page using `grassHelp("r.mapcalc")`. +#' The help page for **GRASS** tool `r.mapcalc` will be especially helpful. You can see this page using `grassHelp("r.mapcalc")`. #' #' @param datatype Character: This ensures that rasters are treated as a certain type before they are operated on. This is useful when using rasters that have all integer values, which **GRASS** can assume represent integers, even if they are not supposed to. In this case, the output of operations on this raster might be an integer if otherwise not corrected. Partial matching is used, and options include: #' * `"integer"`: Force all rasters to integers by truncating their values. The output may still be of type `float` if the operation creates non-integer values. @@ -42,7 +42,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::app()], [terra::lapp()], [subst()], [classify()], and especially the **GRASS** manual page for module `r.mapcalc` (see `grassHelp("r.mapcalc")`) +#' @seealso [terra::app()], [terra::lapp()], [subst()], [classify()], and especially the **GRASS** manual page for tool `r.mapcalc` (see `grassHelp("r.mapcalc")`) #' #' @example man/examples/ex_app.r #' diff --git a/R/as.contour.r b/R/as.contour.r index 30b8ca88..5f113745 100644 --- a/R/as.contour.r +++ b/R/as.contour.r @@ -9,7 +9,7 @@ #' #' @param levels Numeric vector: A numeric vector of values at which to calculate contour lines. Either `nlevels` or `levels` must be specified. #' -#' @seealso [terra::as.contour()], **GRASS** manual page for module `r.contour` (see `grassHelp("r.contour")`) +#' @seealso [terra::as.contour()], **GRASS** manual page for tool `r.contour` (see `grassHelp("r.contour")`) #' #' @returns A `GVector` representing contour lines. #' diff --git a/R/as.lines.r b/R/as.lines.r index 6c5ca388..b7698318 100644 --- a/R/as.lines.r +++ b/R/as.lines.r @@ -6,7 +6,7 @@ #' #' @returns A `GVector`. #' -#' @seealso [as.points()], [as.polygons()], [terra::as.lines()], [thinLines()], [geometry cleaning][breakPolys], and **GRASS** module `r.to.vect` +#' @seealso [as.points()], [as.polygons()], [terra::as.lines()], [thinLines()], [geometry cleaning][breakPolys], and **GRASS** tool `r.to.vect` #' #' @example man/examples/ex_asLines.r #' diff --git a/R/as.polygons.r b/R/as.polygons.r index 94ed9ab2..bc6a34fb 100644 --- a/R/as.polygons.r +++ b/R/as.polygons.r @@ -10,7 +10,7 @@ #' #' @returns A `GVector`. #' -#' @seealso [as.points()], [as.lines()], [terra::as.polygons()], [geometry cleaning][breakPolys], and **GRASS** module `r.to.vect` +#' @seealso [as.points()], [as.lines()], [terra::as.polygons()], [geometry cleaning][breakPolys], and **GRASS** tool `r.to.vect` #' #' @example man/examples/ex_asPolygons.r #' diff --git a/R/centroids.r b/R/centroids.r index b7b7a74c..674597a2 100644 --- a/R/centroids.r +++ b/R/centroids.r @@ -1,11 +1,12 @@ -#' Centroid(s) of a vector +#' Centroid(s) of a vector or clumps in a raster #' -#' @description This function locates the centroid of each geometry of a `GVector`. +#' @description This function locates the centroid of each geometry of a `GVector`, or the centroid of each "clump" of same-valued cells in an integer/categorical raster (for information on types of `GRaster`s, see `vignette("GRasters", package = "fasterRaster")`). #' -#' **To use this function**, you must a) have correctly specified the `addonsDir` option using [faster()], and b) installed the **GRASS** addon `v.centerpoint`. See [addons()] and `vignette("addons", package = "fasterRaster")`. +#' To use this function with a `GVector`, you need the **GRASS** `v.centerpoint` addon. To use the function with a `GRaster`, you need the addon `r.centroids`. In either case, the function will try to install the respective addon (i.e., you need to have an internet connection). Once installed, a tool will not need to be installed again. #' -#' @param x A `GVector`. -#' @param method Character or `NULL` (default): Method used for calculating centroids. The method of calculation depends on whether the input is a `points`, `lines`, or `polygons` `GVector`. If the value is `NULL`, then the default method will be chosen, depending on the geometry type of the `GVector`: +#' @param x A `GVector` or `GRaster`. +#' +#' @param method `GVector`s: Character or `NULL` (default): Method used for calculating centroids. The method of calculation depends on whether the input is a `points`, `lines`, or `polygons` `GVector`. If the value is `NULL`, then the default method will be chosen, depending on the geometry type of the `GVector`: #' * `points`: #' * `"mean"` (default for `points`): Mean of coordinates. #' * `"median"`: Geometric median; more robust to outliers. @@ -21,13 +22,11 @@ #' #' Partial matching is used and case is ignored. #' -#' @param fail Logical: If `TRUE` (default), and the addons folder is not correctly specified, the exit the function with an error. If `FALSE`, then `NULL` will be returned with a warning. -#' -#' @returns A points `GVector`. +#' @returns If the input is a `GVector`, the output will be a "points" `GVector`. If the input is a `GRaster`, the output will be a "points" `GVector` with a table with statistics on each clump. If the input is a `GRaster` with more than one layer, the output will be a `list` of `GVector`s, with one `GVector` per layer. #' #' @example man/examples/ex_centroids.r #' -#' @seealso [terra::centroids()]; **GRASS** addon module `v.centerpoint`. +#' @seealso [terra::centroids()]; **GRASS** addon tools `v.centerpoint` and `r.centroids`. #' #' @aliases centroids #' @rdname centroids @@ -35,10 +34,9 @@ methods::setMethod( f = "centroids", signature = c(x = "GVector"), - function(x, method = NULL, fail = TRUE) { + function(x, method = NULL) { - ok <- addons("v.centerpoint", verbose = TRUE, fail = fail) - if (!ok) return(NULL) + .addons("v.centerpoint") gtype <- geomtype(x) @@ -92,3 +90,62 @@ methods::setMethod( } # EOF ) + +#' @aliases centroids +#' @rdname centroids +#' @exportMethod centroids +methods::setMethod( + f = "centroids", + signature = c(x = "GRaster"), + function(x) { + + .addons("r.centroids") + + .locationRestore(x) + .region(x) + + nLayers <- nlyr(x) + out <- list() + srcs <- .makeSourceName("r_centroids", "vector", n = nLayers) + for (i in 1:nLayers) { + + rawTable <- rgrass::execGRASS( + cmd = "r.centroids", + input = sources(x)[[i]], + output = srcs[i], + flags = c(.quiet(), "overwrite"), + intern = TRUE + ) + + # parse table + rawTable <- rawTable[7:(length(rawTable) - 2)] + lines <- strsplit(rawTable, split = " ") + table <- data.table::data.table() + for (j in seq_along(rawTable)) { + + line <- lines[[j]] + line <- line[line != ""] + line <- as.numeric(line) + table <- rbind( + table, + data.table::data.table( + clump = line[1L], + x = line[5L], + y = line[7L], + numberOfCells = line[4L], + meanCellValue = line[2L], + clumpSum = line[3L] + ) + ) + + } + + out[[i]] <- .makeGVector(srcs[i], table = table) + + } + + if (nLayers == 1) out <- out[[1]] + out + + } # EOF +) diff --git a/R/cleanGeom.r b/R/cleanGeom.r index cd7c2d83..eea39ecb 100644 --- a/R/cleanGeom.r +++ b/R/cleanGeom.r @@ -19,7 +19,7 @@ #' #' @param tolerance Numeric or `NULL` (default): Minimum distance in map units (degrees for unprojected, usually meters for projected) or minimum area (in meters-squared, regardless of projection). #' -#' @seealso [terra::topology()], [fillHoles()], [terra::removeDupNodes()], *Details* section in [fast()], [simplifyGeom()], [smoothGeom()], **GRASS** manual page for module `v.clean` (see `grassHelp("v.clean")`) +#' @seealso [terra::topology()], [fillHoles()], [terra::removeDupNodes()], *Details* section in [fast()], [simplifyGeom()], [smoothGeom()], **GRASS** manual page for tool `v.clean` (see `grassHelp("v.clean")`) #' #' @returns A `GVector`. #' diff --git a/R/clusterPoints.r b/R/clusterPoints.r index aea0eb67..578f22a0 100644 --- a/R/clusterPoints.r +++ b/R/clusterPoints.r @@ -4,7 +4,7 @@ #' #' @param x A "points" `GVector`. #' -#' @param method Character: Method used to identify clusters. Explanations of methods are provided in the help page for the **GRASS** module `v.cluster`, available using `grassHelp("v.cluster")`. +#' @param method Character: Method used to identify clusters. Explanations of methods are provided in the help page for the **GRASS** tool `v.cluster`, available using `grassHelp("v.cluster")`. #' * `"DBSCAN"` (default): Density-Based Spatial Clustering of Applications with Noise. #' * `"DBSCAN2"`: A modification of DBSCAN. #' * `"density"`: Cluster points by relative density. @@ -19,7 +19,7 @@ #' #' @returns A vector of integers indicating the cluster to which each point belongs. #' -#' @seealso **GRASS** manual page for module `v.cluster` (see `grassHelp("v.cluster")`) +#' @seealso **GRASS** manual page for tool `v.cluster` (see `grassHelp("v.cluster")`) #' #' @aliases clusterPoints #' @rdname clusterPoints diff --git a/R/compareGeom.r b/R/compareGeom.r index f47ea40b..7bdcd0cb 100644 --- a/R/compareGeom.r +++ b/R/compareGeom.r @@ -28,7 +28,7 @@ #' #' @param stopOnError Logical: If `TRUE` (default), throw an error with an explanation if the objects are not comparable. If `FALSE` (default), return `TRUE` or `FALSE`. #' -#' @param messages Logical: If `TRUE (default), display a warning if a condition is not met. This only comes into effect if `stopOnError` is `FALSE`. +#' @param messages Logical: If `TRUE` (default), display a warning if a condition is not met. This only comes into effect if `stopOnError` is `FALSE`. #' #' @returns Logical (invisibly): `TRUE` for no mismatches detected, `FALSE` for incompatibility), or side effect of throwing an error. #' diff --git a/R/compositeRGB.r b/R/compositeRGB.r index d753c54d..7bc746f8 100644 --- a/R/compositeRGB.r +++ b/R/compositeRGB.r @@ -14,7 +14,7 @@ #' #' @example man/examples/ex_plot.r #' -#' @seealso [plotRGB()], [terra::plotRGB()], **GRASS** manual page for module `r.composite` (see `grassHelp("r.composite")`) +#' @seealso [plotRGB()], [terra::plotRGB()], **GRASS** manual page for tool `r.composite` (see `grassHelp("r.composite")`) #' #' @aliases compositeRGB #' @rdname compositeRGB diff --git a/R/concats.r b/R/concats.r index ed7f2bc6..b3606f8d 100644 --- a/R/concats.r +++ b/R/concats.r @@ -25,7 +25,7 @@ #' #' @example man/examples/ex_GRaster_categorical.r #' -#' @seealso [combineLevels()], [terra::concats()], `vignette("GRasters", package = "fasterRaster")`, **GRASS** manual page for module `r.cross` (see `grassHelp("r.cross")`) +#' @seealso [combineLevels()], [terra::concats()], `vignette("GRasters", package = "fasterRaster")`, **GRASS** manual page for tool `r.cross` (see `grassHelp("r.cross")`) #' #' @aliases concats #' @rdname concats diff --git a/R/connectors.r b/R/connectors.r index 30d0c944..4f9a9194 100644 --- a/R/connectors.r +++ b/R/connectors.r @@ -7,7 +7,7 @@ #' #' @returns A `GVector` with a data table that has the length of each connecting line in meters. #' -#' @seealso **GRASS** manual for module `v.distance` (see `grassHelp("v.distance")`). +#' @seealso **GRASS** manual for tool `v.distance` (see `grassHelp("v.distance")`). #' #' @example man/examples/ex_connectors.r #' diff --git a/R/convHull.r b/R/convHull.r index 52b55f8b..92ce4fbf 100644 --- a/R/convHull.r +++ b/R/convHull.r @@ -7,7 +7,7 @@ #' #' @return A `GVector`. #' -#' @seealso \code{link[terra]{convHull}}, \code{link[sf]{st_convex_hull}}, module `v.hull` in **GRASS** (see `grassHelp("v.hull")`) +#' @seealso \code{link[terra]{convHull}}, \code{link[sf]{st_convex_hull}}, tool `v.hull` in **GRASS** (see `grassHelp("v.hull")`) #' #' @example man/examples/ex_convHull.r #' diff --git a/R/delaunay.r b/R/delaunay.r index 42d62aab..6502981e 100644 --- a/R/delaunay.r +++ b/R/delaunay.r @@ -6,7 +6,7 @@ #' #' @returns A `GVector`. #' -#' @seealso [terra::delaunay()], module `v.delaunay` in **GRASS** +#' @seealso [terra::delaunay()], tool `v.delaunay` in **GRASS** #' #' @example man/examples/ex_delaunay_voronoi.r #' diff --git a/R/denoise_noise.r b/R/denoise_noise.r index d7a7ef89..6b7b6322 100644 --- a/R/denoise_noise.r +++ b/R/denoise_noise.r @@ -12,7 +12,7 @@ #' #' @returns A multi-layer `GRaster` with one layer per input. #' -#' @seealso [princomp()], [stats::prcomp()], **GRASS** manual page for module `i.pca` (see `grassHelp("i.pca")`) +#' @seealso [princomp()], [stats::prcomp()], **GRASS** manual page for tool `i.pca` (see `grassHelp("i.pca")`) #' #' @example man/examples/ex_denoise_noise.r #' diff --git a/R/fast.r b/R/fast.r index a1128d24..7a09fa81 100644 --- a/R/fast.r +++ b/R/fast.r @@ -62,12 +62,12 @@ #' Issues can also arise due to: #' #' * **Data table-vector mismatching**: If your vector has a data table ("attribute table") associated with it, errors can occur if there are more/fewer geometries (or multi-geometries) per row in the table. If you do not really need the data table to do your analysis, you can remove it (and thus obviate this error) using `dropTable = TRUE`. -#' * **Dissolving or aggregating "invalid" geometries**: Using the `resolve` argument, you can create a topologically valid vector by either coercing all overlapping portions of polygons into their own geometries (`resolve = "disaggregate"`), or by coercing them into a single, combined geometry (`resolve = "aggregate"`). Aggregation/disaggregation will be implemented after loading the vector into **GRASS** using the settings given by `snap` and `area`. Aggregation/disaggregation will cause any associated data table to be dropped (it forces `dropTable` to be `TRUE`). The default action is to do neither aggregation nor disaggregation (`resolve = NA`). +#' * **Dissolving or aggregating "invalid" geometries**: Using the `resolve` argument, you can create a topologically valid vector by either coercing all overlapping portions of polygons into their own geometries (`resolve = "disaggregate"`), or by coercing them into a single, combined geometry (`resolve = "aggregate"`). Aggregation/disaggregation will be implemented after loading the vector into **GRASS** using the settings given by `snap` and `area`. Aggregation/disaggregation will cause any associated data table to be dropped (it forces `dropTable` to be `TRUE`). The default action is to do neither aggregation nor disaggregation (`resolve = NA`). You can also do this outside **fasterRaster** using [terra::aggregate()] or [terra::disagg()]. #' #' If none of these fixes work, you can try: #' -#' * **Correction outside of *fasterRaster***: Before you convert the vector into **fasterRaster**'s `GVector` format, you can also try using the [terra::makeValid()] or [sf::st_make_valid()] tools to fix issues, then use `fast()`. -#' * **Post-conversion to a `GVector`**: If you do get a vector loaded into `GVector` format, you can also use a set of **fasterRaster** vector-manipulation [tools][breakPolys] or [fillHoles()] to fix issues. +#' * **Correction outside of *fasterRaster***: Before you convert the vector into **fasterRaster**'s `GVector` format, you can also try using the [terra::makeValid()] or [sf::st_make_valid()] tools to fix issues, then use `fast()`. You can also use [terra::aggregate()] or [terra::disagg()] to combine/split problematic geometries. +#' * **Post-load correction**: If you do get a vector loaded into `GVector` format, you can also use a set of **fasterRaster** vector-manipulation [tools][breakPolys] or [fillHoles()] to fix issues. #' #' @seealso \code{\link[rgrass]{read_RAST}} and \code{\link[rgrass]{read_VECT}}, [vector cleaning][breakPolys], [fillHoles()], plus **GRASS** modules `v.in.ogr` (see `grassHelp("v.in.ogr")`) and `r.import` (`grassHelp("r.import")`) #' @@ -116,6 +116,9 @@ methods::setMethod( if (is.na(faster("grassDir"))) stop("You must specify the folder in which GRASS is installed using faster().") + # Error for cases where there are fewer geometries than rows in the data table. Topology correction using `snap` or `area` can only the number of geometries, so if the number of geometries is larger than the number of table rows, then iteratively trying larger values of `snap` or `area` will continue to create a mismatch between the number of geometries and table rows. In this case, just throw an error to obviate wasting time. + nGeometriesVsTableRowsError <- "Since the data table has more rows than there are vector geometries,\n increasing `snap` and/or `area` can only decrease the number of geometries.\n Try smaller values of `snap` and/or `area`, or remove the table using\n `dropTable = TRUE`." + ### dots ######## @@ -329,16 +332,14 @@ methods::setMethod( if ((verbose | faster("verbose")) & gtype == "area") { omnibus::say("Creating GVector with ", thisSnapNice, " snapping and ", thisAreaNice, "...") - }# else if (verbose | faster("verbose")) { - # omnibus::say("Creating GVector with ", thisSnapNice, " snapping of vertices/points...") - #} + } src <- .makeSourceName("fast_v_in_ogr", "vector") if (is.null(snap) & (is.null(area) || area == 0)) { # slower if we need to record messages suppressMessages( - run <- rgrass::execGRASS( + assessment <- rgrass::execGRASS( cmd = "v.in.ogr", input = x, output = src, @@ -353,9 +354,9 @@ methods::setMethod( ) valid <- !any(c( - grepl(run, pattern = "WARNING: The output contains topological errors"), - grepl(run, pattern = "Invalid argument"), - run == "1" + grepl(assessment, pattern = "WARNING: The output contains topological errors"), + grepl(assessment, pattern = "Invalid argument"), + assessment == "1" )) if (valid) { # more thorough test... slower @@ -376,6 +377,9 @@ methods::setMethod( if (!valid & verbose & !dropTable) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries, ", sum(is.na(info$cats)), " invalid geometries, and ", nrow(table), " rows in its data table.") + if (info$nGeometries < nrow(table)) { + stop(nGeometriesVsTableRowsError) + } } else if (!valid & verbose) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries and ", sum(is.na(info$cats)), " invalid geometries.") } @@ -411,6 +415,9 @@ methods::setMethod( if (!valid & verbose & !dropTable) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries, ", sum(is.na(info$cats)), " invalid geometries, and ", nrow(table), " rows in its data table.") + if (info$nGeometries < nrow(table)) { + stop(nGeometriesVsTableRowsError) + } } else if (!valid & verbose) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries and ", sum(is.na(info$cats)), " invalid geometries.") } @@ -420,8 +427,27 @@ methods::setMethod( ### automated vector topology correction if (!valid & (is.null(snap) | is.null(area))) { + if (!exists("assessment", inherits = FALSE)) { + + suppressMessages( + assessment <- rgrass::execGRASS( + cmd = "v.in.ogr", + input = x, + output = src, + snap = thisSnap, + min_area = thisArea, + flags = c("verbose", "overwrite", "t", "o", correctTopoFlag), + ignore.stderr = FALSE, + Sys_show.output.on.console = FALSE, + echoCmd = FALSE, # displays GRASS command + intern = TRUE + ) + ) + + } + stepsMinus1 <- steps - 1L - snapRange <- run[grepl(run, pattern = "Estimated range of snapping threshold:")] + snapRange <- assessment[grepl(assessment, pattern = "Estimated range of snapping threshold:")] # generic snap range if (length(snapRange) == 0L) { @@ -496,6 +522,9 @@ methods::setMethod( if (made & !valid & verbose & !dropTable) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries, ", sum(is.na(info$cats)), " invalid geometries, and ", nrow(table), " rows in its data table.") + if (info$nGeometries < nrow(table)) { + stop(nGeometriesVsTableRowsError) + } } else if (made & !valid & verbose) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries and ", sum(is.na(info$cats)), " invalid geometries.") } else if (!made) { @@ -554,6 +583,9 @@ methods::setMethod( if (made & !valid & verbose & !dropTable) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries, ", sum(is.na(info$cats)), " invalid geometries, and ", nrow(table), " rows in its data table.") + if (info$nGeometries < nrow(table)) { + stop(nGeometriesVsTableRowsError) + } } else if (made & !valid & verbose) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries and ", sum(is.na(info$cats)), " invalid geometries.") } else if (!made) { @@ -615,6 +647,9 @@ methods::setMethod( if (made & !valid & verbose & !dropTable) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries, ", sum(is.na(info$cats)), " invalid geometries, and ", nrow(table), " rows in its data table.") + if (info$nGeometries < nrow(table)) { + stop(nGeometriesVsTableRowsError) + } } else if (made & !valid & verbose) { omnibus::say(" Vector has ", info$nGeometries, " valid geometries and ", sum(is.na(info$cats)), " invalid geometries.") } else if (!made) { @@ -635,7 +670,40 @@ methods::setMethod( stop(msg) } + out <- .makeGVector(src = src, table = table) + + # # save/reload vector... seems to fix errors with subset_single_bracket on polygon vectors later on + # if (reload & geomtype(out) == "polygons") { + + # if (verbose | faster("verbose")) omnibus::say('Reloading GVector...') + # tempVect <- tempfile(fileext = ".gpkg") + + # args <- list( + # cmd = "v.out.ogr", + # input = sources(out), + # output = tempVect, + # format = "GPKG", + # flags = c(.quiet(), "s", "overwrite") + # # flags = c(.quiet(), "s", "c") # "c" ==> save geometries lacking a cat number + # ) + # do.call(rgrass::execGRASS, args) + + # Sys.sleep(0.5) + # src <- .makeSourceName("v_in_ogr", "vector") + # rgrass::execGRASS( + # cmd = "v.in.ogr", + # input = tempVect, + # output = src, + # flags = c(.quiet(), "overwrite", "t", "c") + # ) + # out <- .makeGVector(src, table = table) + + # # writeVector(out, filename = tempVect, overwrite = TRUE) + # # out <- fast(tempVect, reload = FALSE, table = table) # cannot use vect() on this... weird! + + # } + if ((verbose | faster("verbose")) & geomtype(out) == "polygons") omnibus::say("Topologically valid vector created.") } # x is a filename and xVect supplied diff --git a/R/fasterRaster.r b/R/fasterRaster.r index a0649f5e..f8754c95 100644 --- a/R/fasterRaster.r +++ b/R/fasterRaster.r @@ -1,17 +1,15 @@ -#' "fasterRaster": Faster raster and spatial vector processing using "GRASS GIS" +#' "fasterRaster": Faster raster and spatial vector processing using "GRASS" #' -#' @description **fasterRaster**: Processing of large-in-memory/-on disk rasters and spatial vectors in using **GRASS GIS**. Most functions in the **terra** and **sf** packages are recreated. Processing of medium-sized and smaller spatial objects will nearly always be faster using **terra** or **sf**. To use most of the functions you must have the stand-alone version of **GRASS GIS** version 8.3 or higher (not the **OSGeoW4** installer version). Note that due to differences in how **GRASS**, **terra**, and **sf** were implemented, results will not always be strictly comparable between functions for the same operation. +#' @description **fasterRaster**: Processing of large-in-memory/-on disk rasters and spatial vectors in using **GRASS**. Most functions in the **terra** and **sf** packages are recreated. Processing of medium-sized and smaller spatial objects will nearly always be faster using **terra** or **sf**. To use most of the functions you must have the stand-alone version of **GRASS** version 8.3 or higher (not the **OSGeoW4** installer version). Note that due to differences in how **GRASS**, **terra**, and **sf** were implemented, results will not always be strictly comparable between functions for the same operation. #' #' ## Most useful tutorials and functions: #' * The quick-start guide to getting started with **fasterRaster**: `vignette("fasterRaster", package = "fasterRaster")`: #' * Types of `GRaster`s: `vignette("GRasters", package = "fasterRaster")` #' * How to speed up **fasterRaster**: `vignette("faster_fasterRaster", package = "fasterRaster")` -#' * Using functions that depend on **GRASS** addons: `vignette("addons", package = "fasterRaster")` #' * [faster()]: Set the directory where **GRASS** is installed on your system, and set or get other package-wide options. This function must be run once before using most **fasterRaster** functions. #' * [fast()]: Convert a `SpatRaster`, `SpatVector`, or `sf` vector to **fasterRaster**'s raster format (`GRaster`s) or vector format (`GVector`s), or load one from a file #' * [rast()], [vect()], and [st_as_sf()]: Convert `GRaster`s and `GVector`s to `SpatRaster`s, `SpatVector`s, or `sf` vectors #' * [writeRaster()] and [writeVector()]: Save `GRaster`s or `GVector`s to disk -#' * [addons()]: Test if the `addons` directory is correct and if a particular addon **GRASS** module is installed. #' #' ## Properties of `GRasters` #' * [crs()]: Coordinate reference system @@ -99,6 +97,7 @@ #' * [maskNA()]: Mask all non-NA cells or all NA cells #' * [match()], \code{\link[fasterRaster]{%in%}}, and \code{\link[fasterRaster]{%notin%}}: Find which cells of a `GRaster` match or do not match certain values #' * [merge()]: Combine two or more rasters with different extents and fill in `NA`s +#' * [multivarEnvSim()]: Multivariate environmental similarity surface (MESS) #' * \code{\link[fasterRaster]{names<-}}: Assign names to a `GRaster` #' * [noise()]: Remove coarse-scale trends from a `GRaster`, leaving just fine-scale "noise" #' * [pairs()]: Plot correlations between `GRaster` layers @@ -126,9 +125,10 @@ #' * [fractalRast()]: Create a fractal `GRaster` #' * [init()]: GRaster with values equal to row, column, coordinate, regular, or "chess" #' * [longlat()]: Create longitude/latitude rasters -#' * [rnormRast()]: A random `GRaster` with values drawn from a normal distribution +#' * [rNormRast()]: A random `GRaster` with values drawn from a normal distribution #' * [rSpatialDepRast()]: Create a random `GRaster` with or without spatial dependence -#' * [runifRast()]: A random `GRaster` with values drawn from a uniform distribution +#' * [rUnifRast()]: A random `GRaster` with values drawn from a uniform distribution +#' * [rWalkRast()]: Paths of random walkers #' * [sineRast()]: Sine wave rasters #' #' ## Analysis of terrain and hydrology @@ -235,6 +235,7 @@ #' * [kernel()]: Kernel density estimator of points #' * [missing.cases()]: Find rows of a `GVector`'s data table that have at least `NA` in them #' * \code{\link[fasterRaster]{names<-}}: Assign names to columns of a `GVector`s data table +#' * [neighborhoodMatrix()] and [neighbourhoodMatrix()]: Neighborhood matrix of a polygons `GVector` #' * [project()]: Change coordinate reference system #' * [rasterize()]: Convert a `GVector` to a `GRaster` #' * [rbind()]: Combine `GVectors` @@ -283,15 +284,18 @@ #' * [vect()]: Convert a `GVector` to a `SpatVector` #' #' ## General purpose functions +#' * [addons()]: Show installed **GRASS** addons #' * [compareGeom()]: Determine if geographic metadata is same between `GRaster`s and/or `GVector`s #' * [dropRows()]: Remove rows from a `data.frame` or `data.table` #' * [grassGUI()]: Start the **GRASS** GUI (not recommended for most users!!!) -#' * [grassHelp()]: Open the help page for a **GRASS** module. +#' * [grassHelp()]: Open the help page for a **GRASS** tool. #' * [grassInfo()]: **GRASS** version and citation #' * [grassStarted()]: Has a connection **GRASS** been made within the current **R** session? +#' * [installAddon()]: Install a **GRASS** addon #' * [mow()]: Remove unused rasters and vectors from the **GRASS** cache #' * [reorient()]: Convert degrees between 'north-orientation' and 'east orientation' #' * [replaceNAs()]: Replace `NA`s in columns of a `data.table` or `data.frame`, or in a vector +#' * [removeAddon()]: Delete **GRASS** addon from your system #' * [seqToSQL()]: Format a numeric series into an SQL value call #' * [update()]: Refresh metadata in a `GRaster` or `GVector` object #' diff --git a/R/fillHoles.r b/R/fillHoles.r index 54c9dcc5..8d893fbd 100644 --- a/R/fillHoles.r +++ b/R/fillHoles.r @@ -10,7 +10,7 @@ #' #' @example man/examples/ex_GVector.r #' -#' @seealso [terra::fillHoles()], **GRASS** manual page for module `v.fill.holes` (see `grassHelp("v.fill.holes")`) +#' @seealso [terra::fillHoles()], **GRASS** manual page for tool `v.fill.holes` (see `grassHelp("v.fill.holes")`) #' #' @aliases fillHoles #' @rdname fillHoles diff --git a/R/fillNAs.r b/R/fillNAs.r index c5d2f1a9..71269423 100644 --- a/R/fillNAs.r +++ b/R/fillNAs.r @@ -18,7 +18,7 @@ #' #' @example man/examples/ex_fillNAs.r #' -#' @seealso [terra::interpNear()], **GRASS** module `r.fillnulls` (see `grassHelp("r.fillnulls")`) +#' @seealso [terra::interpNear()], **GRASS** tool `r.fillnulls` (see `grassHelp("r.fillnulls")`) #' #' @aliases fillNAs #' @rdname fillNAs diff --git a/R/flow.r b/R/flow.r index e3c347a2..9120d01a 100644 --- a/R/flow.r +++ b/R/flow.r @@ -7,7 +7,7 @@ #' * Flooded areas; and/or #' * Topographic convergence (log of flow accumulation divided by local slope). #' -#' More details about the computations can be found at the help page for the **GRASS** module `r.terraflow`] (see `grassHelp("r.terraflow")`) +#' More details about the computations can be found at the help page for the **GRASS** tool `r.terraflow`] (see `grassHelp("r.terraflow")`) #' #' @param x A `GRaster` with a single layer, typically representing elevation. #' @@ -23,9 +23,9 @@ #' * `"TCI"`: Topographic convergence index #' * `"*"`: All of the above #' -#' @seealso [flowPath()], [streams()], the **GRASS** module `r.terraflow` (see `grassHelp("r.terraflow")`) +#' @seealso [flowPath()], [streams()], the **GRASS** tool `r.terraflow` (see `grassHelp("r.terraflow")`) #' -#' @param scratchDir Character or `NULL` (default): Directory in which to store temporary files. The **GRASS** module `r.terraflow` makes a lot of temporary files. If this is `NULL`, then a temporary folder in the user's working directory will be used (see [getwd()]). +#' @param scratchDir Character or `NULL` (default): Directory in which to store temporary files. The **GRASS** tool `r.terraflow` makes a lot of temporary files. If this is `NULL`, then a temporary folder in the user's working directory will be used (see [getwd()]). #' #' @returns A `GRaster`. #' diff --git a/R/flowPath.r b/R/flowPath.r index b9baeb27..35da5a3a 100644 --- a/R/flowPath.r +++ b/R/flowPath.r @@ -17,7 +17,7 @@ #' #' @example man/examples/ex_flowPath.r #' -#' @seealso [flow()], [streams()], the **GRASS** module `r.drain` (see `grassHelp("r.drain")`) +#' @seealso [flow()], [streams()], the **GRASS** tool `r.drain` (see `grassHelp("r.drain")`) #' #' @aliases flowPath #' @rdname flowPath diff --git a/R/focal.r b/R/focal.r index f7af1e9e..35efa11d 100644 --- a/R/focal.r +++ b/R/focal.r @@ -16,13 +16,13 @@ #' * "`min`" or "`max`": Minimum or maximum. Should not use a weights matrix. #' * "`range`": Difference between the maximum and minimum. Should not use a weights matrix. #' * "`sd`": Sample standard deviation. NB: This is the same as the [stats::sd()] function. -#' * "`sdpop`": Population standard deviation. NB: This is the same as the function "stddev" in the **GRASS** module `r.neighbors`. +#' * "`sdpop`": Population standard deviation. NB: This is the same as the function "stddev" in the **GRASS** tool `r.neighbors`. #' * "`sum`": Sum of non-`NA`` cells. #' * "`count`": Number of non-`NA cells. Should not use a weights matrix. #' * "`var`": Sample variance. NB: This is the same as the [stats::var()] function. -#' * "`varpop`": Population variance. NB: This is the same as the function "variance" in the **GRASS** module `r.neighbors`. +#' * "`varpop`": Population variance. NB: This is the same as the function "variance" in the **GRASS** tool `r.neighbors`. #' * "`nunique`": Number of unique values. Should not use a weights matrix. -#' * "`interspersion`": Proportion of cells with values different from focal cell (e.g., if 6 of 8 cells have different values, then the interspersion is 6/8 = 0.75). NB: This is slightly different from how it is defined in the **GRASS** module `r.neighbors`. Should not use a weights matrix. +#' * "`interspersion`": Proportion of cells with values different from focal cell (e.g., if 6 of 8 cells have different values, then the interspersion is 6/8 = 0.75). NB: This is slightly different from how it is defined in the **GRASS** tool `r.neighbors`. Should not use a weights matrix. #' * "`quantile`": Quantile of values. The value in argument `quantile` is used to specify the quantile. #' #' The center cell value is always included in the calculations, and all calculations ignore `NA` cells (i.e., they do not count as cells in the focal neighborhood). @@ -33,7 +33,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::focal()], **GRASS** manual page for module `r.neighbors` (see `grassHelp("r.neighbors")`) +#' @seealso [terra::focal()], **GRASS** manual page for tool `r.neighbors` (see `grassHelp("r.neighbors")`) #' #' @example man/examples/ex_focal.r #' diff --git a/R/fractalRast.r b/R/fractalRast.r index fc3dd5e0..08f29be6 100644 --- a/R/fractalRast.r +++ b/R/fractalRast.r @@ -14,7 +14,7 @@ #' #' @example man/examples/ex_randRast.r #' -#' @seealso [rSpatialDepRast()], [rnormRast()], [runifRast()], **GRASS** manual page for module `r.surf.fractal` (see `grassHelp("r.surf.fractal")`) +#' @seealso [rSpatialDepRast()], [rNormRast()], [rUnifRast()], [rWalkRast()], **GRASS** manual page for tool `r.surf.fractal` (see `grassHelp("r.surf.fractal")`) #' #' @aliases fractalRast #' @rdname fractalRast diff --git a/R/fragmentation.r b/R/fragmentation.r index 7675248c..e351784f 100644 --- a/R/fragmentation.r +++ b/R/fragmentation.r @@ -2,7 +2,7 @@ #' #' @description Riitters et al. (2020) propose a classification scheme for forest fragmentation (which can be applied to any habitat type). The scheme relies on calculating density (e.g., number of forested cells in a window around a focal cell) and connectivity (number of cases where neighboring cells are both forested). This function calculates these classes from a `GRaster` or `SpatRaster` in which the focal habitat type has cell values of 1, and non-focal habitat type has cell values of 0 or `NA`. #' -#' Note that by default, the `SpatRaster` and `GRaster` versions will create different results around the border of the raster. The `SpatRaster` version uses the [terra::focal()] function, which will not return an `NA` value when its window overlaps the raster border if the `na.rm` argument is `TRUE`. However, the `GRaster` version uses the **GRASS** module `r.neighbors`, which does return `NA` values in these cases. +#' Note that by default, the `SpatRaster` and `GRaster` versions will create different results around the border of the raster. The `SpatRaster` version uses the [terra::focal()] function, which will not return an `NA` value when its window overlaps the raster border if the `na.rm` argument is `TRUE`. However, the `GRaster` version uses the **GRASS** tool `r.neighbors`, which does return `NA` values in these cases. #' #' The fragmentation classes are: #' * Value provided by `none`: None (i.e., no forest; default is `NA`). diff --git a/R/freq.r b/R/freq.r index 397504db..9476bf7d 100644 --- a/R/freq.r +++ b/R/freq.r @@ -12,7 +12,7 @@ #' #' @returns A `data.frame` or a named `list` of `data.frame`s, one per layer in `x`. #' -#' @seealso [terra::freq()], module `r.stats` in **GRASS** +#' @seealso [terra::freq()], tool `r.stats` in **GRASS** #' #' @example man/examples/ex_freq.r #' diff --git a/R/g.proj.r b/R/g.proj.r index 0de0962b..cb1683b9 100644 --- a/R/g.proj.r +++ b/R/g.proj.r @@ -1,6 +1,6 @@ -#' Call GRASS `g.proj` module +#' Call GRASS `g.proj` tool #' -#' This function calls the **GRASS** module `g.region` to display information on the projection of the current **GRASS** "project". +#' This function calls the **GRASS** tool `g.region` to display information on the projection of the current **GRASS** "project". #' #' @returns Displays current projection information for the active "project/location" in **GRASS**. #' diff --git a/R/g.region.r b/R/g.region.r index cfd7633f..e046ad0d 100644 --- a/R/g.region.r +++ b/R/g.region.r @@ -1,6 +1,6 @@ -#' Call GRASS `g.region` module +#' Call GRASS `g.region` tool #' -#' This function calls the **GRASS** module `g.region` to display information on the region of the current **GRASS** "project". +#' This function calls the **GRASS** tool `g.region` to display information on the region of the current **GRASS** "project". #' #' @returns Displays current region information for the active "project/location" in **GRASS**. #' diff --git a/R/geomorphons.r b/R/geomorphons.r index c502981b..56a68e39 100644 --- a/R/geomorphons.r +++ b/R/geomorphons.r @@ -1,6 +1,6 @@ #' Identify terrain feature types #' -#' @description Geomorphons are idealized terrain types calculated from an elevator raster based on a moving window of a given size. The window is a torus (which can have an inner radius of 0, so can also be a circle), which allows it to identify geomorphons of a given size while ignoring ones larger or smaller. There are 10 basic geomorphons. Consult the the manual for **GRASS** module `r.geomorphon` using `grassHelp("r.geomorphon")` for more details and diagrams of each type of geomorphon. Geomorphon types include: +#' @description Geomorphons are idealized terrain types calculated from an elevator raster based on a moving window of a given size. The window is a torus (which can have an inner radius of 0, so can also be a circle), which allows it to identify geomorphons of a given size while ignoring ones larger or smaller. There are 10 basic geomorphons. Consult the the manual for **GRASS** tool `r.geomorphon` using `grassHelp("r.geomorphon")` for more details and diagrams of each type of geomorphon. Geomorphon types include: #' 1. Flat areas: Focal area has approximately the same elevation as surrounding areas #' 2. Pits: An area is lower than all other surrounding areas #' 3. Valley: Focal area has elevation similar to two opposing side of the window but lower than the other two opposing sides @@ -23,13 +23,13 @@ #' @param flatDist Numeric: Distance (in meters) to correct for the effect of large distances on the diminished capacity to identify "flat" geomorphons. If the distance between the focal area and a surrounding area surpasses this distance, then the effective value of `flat` will be reduced #' #' @param mode Character: Method for implementing the zenith/line-of-site search. Partial matching is used: -#' * `"1"` (default): The "original" geomorphon mode (in **GRASS** module `r.geomorphon`, the "anglev1" method) +#' * `"1"` (default): The "original" geomorphon mode (in **GRASS** tool `r.geomorphon`, the "anglev1" method) #' * `"2"`: Better handling of cases with equal zenith/nadir angles (the "anglev2" method) #' * `"2d"`: As `"2"`, but takes into account zenith/nadir distance ("anglev2_distance" method) #' #' @returns A categorical `GRaster` where each geomorphon is a category (see `vignette("GRasters", package = "fasterRaster")`). #' -#' @seealso **GRASS** manual for module `r.geomorphon` (see `grassHelp("r.geomorphon")`) +#' @seealso **GRASS** manual for tool `r.geomorphon` (see `grassHelp("r.geomorphon")`) #' #' @example man/examples/ex_geomorphons.r #' diff --git a/R/global.r b/R/global.r index b8f64b14..a58173b5 100644 --- a/R/global.r +++ b/R/global.r @@ -26,7 +26,7 @@ #' #' @returns If `x` is missing, the function returns a character vector of all accepted function names. If `x` is a `GRaster`, a data frame with the specified statistics is returned. #' -#' @seealso [terra::global()] and **GRASS** module `r.univar` +#' @seealso [terra::global()] and **GRASS** tool `r.univar` #' #' @example man/examples/ex_global.r #' diff --git a/R/grassHelp.r b/R/grassHelp.r index 91d1fcd8..07e84482 100644 --- a/R/grassHelp.r +++ b/R/grassHelp.r @@ -1,9 +1,9 @@ -#' Open the help page for a GRASS module +#' Open the help page for a GRASS tool #' -#' @description This function opens the manual page for a **GRASS** module (function) in your browser. +#' @description This function opens the manual page for a **GRASS** tool (function) in your browser. #' #' @param x Character: Any of: -#' * The name of a **GRASS** module (e.g., `"r.mapcalc"`). +#' * The name of a **GRASS** tool (e.g., `"r.mapcalc"`). #' * `"toc"`: **GRASS** manual table of contents. #' * `"index"`: Display an index of topics. #' diff --git a/R/grid.r b/R/grid.r index 9fb06c51..60fe6f73 100644 --- a/R/grid.r +++ b/R/grid.r @@ -17,7 +17,7 @@ #' #' @example man/examples/ex_grid_hexagons.r #' -#' @seealso [hexagons()], module `v.mkgrid` in **GRASS** +#' @seealso [hexagons()], tool `v.mkgrid` in **GRASS** #' #' @aliases grid #' @rdname grid diff --git a/R/hexagons.r b/R/hexagons.r index f3f67bcb..437f572d 100644 --- a/R/hexagons.r +++ b/R/hexagons.r @@ -14,7 +14,7 @@ #' #' @example man/examples/ex_grid_hexagons.r #' -#' @seealso [grid()], module `v.mkgrid` in **GRASS** +#' @seealso [grid()], tool `v.mkgrid` in **GRASS** #' #' @aliases hexagons #' @rdname hexagons diff --git a/R/hillshade.r b/R/hillshade.r index 0d0f8ffc..f26517d4 100644 --- a/R/hillshade.r +++ b/R/hillshade.r @@ -6,7 +6,7 @@ #' #' @param angle Numeric: The altitude of the sun above the horizon in degrees. Valid values are in the range \[0, 90\], and the default value is 45 (half way from the horizon to overhead). #' -#' @param direction The direction (azimuth) in which the sun is shining in degrees. Valid values are in the range 0 to 360. The default is 0, meaning the sun is at due south (180 degrees) and shining due north (0 degrees). Note that in this function, 0 corresponds to north and 180 to south, but in the **GRASS** module `r.relief`, "east orientation" is used (0 is east, 90 is north, etc.). +#' @param direction The direction (azimuth) in which the sun is shining in degrees. Valid values are in the range 0 to 360. The default is 0, meaning the sun is at due south (180 degrees) and shining due north (0 degrees). Note that in this function, 0 corresponds to north and 180 to south, but in the **GRASS** tool `r.relief`, "east orientation" is used (0 is east, 90 is north, etc.). #' #' @param zscale Numeric: Value by which to exaggerate terrain. The default is 1. Numbers greater than this will increase apparent relief, and less than this (even negative) will diminish it. #' diff --git a/R/horizonHeight.r b/R/horizonHeight.r index 7f092f9d..288e32c0 100644 --- a/R/horizonHeight.r +++ b/R/horizonHeight.r @@ -8,7 +8,7 @@ #' #' @param step Numeric integer between 0 and 360, inclusive: Angle step size (in degrees) for calculating horizon height. The direction in which horizon height is calculated is incremented from 0 to 360, with the last value excluded. #' -#' @param northIs0 Logical: If `TRUE` (default), horizon height calculated in the 0-degree direction will be facing north, and proceed clockwise So, under "north orientation", 0 is north, 90 east, 180 south, and 270 west. If `FALSE`, angles are in "east orientation", and proceed counterclockwise from east. So, east is 0, north 90, west 180, and south 270. North orientation is the default for this function in **R**, but east orientation is the default in the **GRASS** module `r.horizon`. **Note:** The [sun()] function requires aspect to be in east orientation. +#' @param northIs0 Logical: If `TRUE` (default), horizon height calculated in the 0-degree direction will be facing north, and proceed clockwise So, under "north orientation", 0 is north, 90 east, 180 south, and 270 west. If `FALSE`, angles are in "east orientation", and proceed counterclockwise from east. So, east is 0, north 90, west 180, and south 270. North orientation is the default for this function in **R**, but east orientation is the default in the **GRASS** tool `r.horizon`. **Note:** The [sun()] function requires aspect to be in east orientation. #' #' @param bufferZone Numeric >= 0 (default is 0): A buffer of the specified width will be generated around the raster before calculation of horizon angle. If the coordinate system is in longitude/latitude (e.g., WGS84 or NAD83), then this is specified in degrees. Otherwise units are map units (usually meters). #' @@ -18,7 +18,7 @@ #' #' @returns A `GRaster` with one or more layers. The layers will be named `height_`*xyz*, where *xyz* is degrees from north or from east, depending on whether north or east orientation is used. #' -#' @seealso **GRASS** manual page for module `r.horizon` (see `grassHelp("r.horizon")`) +#' @seealso **GRASS** manual page for tool `r.horizon` (see `grassHelp("r.horizon")`) #' #' @example man/examples/ex_horizonHeight.r #' diff --git a/R/interpIDW.r b/R/interpIDW.r index dc671f49..efac9bef 100644 --- a/R/interpIDW.r +++ b/R/interpIDW.r @@ -14,7 +14,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::interpIDW()], [interpSplines()], [fillNAs()], **GRASS** module `v.surf.idw` (se `grassHelp("v.surf.idw")`) +#' @seealso [terra::interpIDW()], [interpSplines()], [fillNAs()], **GRASS** tool `v.surf.idw` (se `grassHelp("v.surf.idw")`) #' #' @aliases interpIDW #' @rdname interpIDW diff --git a/R/interpSplines.r b/R/interpSplines.r index 6e4b3cc5..eff72675 100644 --- a/R/interpSplines.r +++ b/R/interpSplines.r @@ -29,7 +29,7 @@ #' * `lambda` is `NULL` and `interpolate` is `FALSE`: A `data.frame` with values of `lambdas` that were assessed, plus `mean` (mean residual value) and `rms` (root mean square error). You can see the table using `attr(output_raster, "lambdas", exact = TRUE)`. #' * `lambda` is a number (`interpolate` is ignored): A `GRaster`. #' -#' @seealso [interpIDW()], [fillNAs()], **GRASS** module `v.surf.bspline` (see `grassHelp("v.surf.bspline")`) +#' @seealso [interpIDW()], [fillNAs()], **GRASS** tool `v.surf.bspline` (see `grassHelp("v.surf.bspline")`) #' #' @aliases interpSplines #' @rdname interpSplines diff --git a/R/kernel.r b/R/kernel.r index 87d9823e..b2d69a8f 100644 --- a/R/kernel.r +++ b/R/kernel.r @@ -28,7 +28,7 @@ #' #' Otherwise, if `h` is `NULL`, then the value will be arbitrarily set at 1/5th of the shorter of the distance of the x- and y-extent of the points. #' -#' @seealso **GRASS** manual page for module `v.kernel` (see `grassHelp("v.kernel")`) +#' @seealso **GRASS** manual page for tool `v.kernel` (see `grassHelp("v.kernel")`) #' #' @returns A `GRaster`. #' diff --git a/R/locationCreate.r b/R/locationCreate.r index 330e4c63..e8052a74 100644 --- a/R/locationCreate.r +++ b/R/locationCreate.r @@ -144,7 +144,7 @@ methods::setMethod( suppressWarnings( session <- rgrass::initGRASS( gisBase = grassDir, - addon_base = addonsDir, + # addon_base = addonsDir, home = workDir, gisDbase = workDir, # ? SG = emptyRast, diff --git a/R/locationRestore.r b/R/locationRestore.r index 79a2fde2..f38134b5 100644 --- a/R/locationRestore.r +++ b/R/locationRestore.r @@ -80,7 +80,7 @@ methods::setMethod( # suppressWarnings( # session <- rgrass::initGRASS( # gisBase = grassDir, - # addon_base = addonsDir, + # # addon_base = addonsDir, # home = workDir, # gisDbase = workDir, # ? # SG = emptyRast, diff --git a/R/makeSourceName.r b/R/makeSourceName.r index 5175783b..d8c7966a 100644 --- a/R/makeSourceName.r +++ b/R/makeSourceName.r @@ -1,6 +1,6 @@ #' Make unique GRASS name for rasters, vectors, etc. #' -#' @param x Character or `NULL`: Descriptive string. **Developers, please note**: To assist with debugging, **GRASS** objects created by a **GRASS** module have the module named in this argument (with underscores). Example: "v_in_ogr" or "r_resample". +#' @param x Character or `NULL`: Descriptive string. **Developers, please note**: To assist with debugging, **GRASS** objects created by a **GRASS** tool have the tool named in this argument (with underscores). Example: "v_in_ogr" or "r_resample". #' #' @param type Character: `raster`, `raster3D`, `vector`, or `table`. #' diff --git a/R/mask.r b/R/mask.r index f6f5c330..5fcccab4 100644 --- a/R/mask.r +++ b/R/mask.r @@ -14,7 +14,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::mask()], **GRASS** module `r.mask` +#' @seealso [terra::mask()], **GRASS** tool `r.mask` #' #' @example man/examples/ex_mask.r #' diff --git a/R/merge.r b/R/merge.r index c7b549a7..46fe94cf 100644 --- a/R/merge.r +++ b/R/merge.r @@ -6,7 +6,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::merge()], [terra::mosaic()], and **GRASS** module `r.patch` +#' @seealso [terra::merge()], [terra::mosaic()], and **GRASS** tool `r.patch` #' #' @example man/examples/ex_merge.r #' diff --git a/R/multivarEnvSim.r b/R/multivarEnvSim.r new file mode 100644 index 00000000..76e1e90d --- /dev/null +++ b/R/multivarEnvSim.r @@ -0,0 +1,197 @@ +#' Multivariate environmental similarity surface (MESS) +#' +#' @description The multivariate environmental similarity surface (MESS) indicates the degree to which a set of "projection" environmental conditions fall inside or outside a set of "reference" conditions. Values of 1 indicate a location falls at the exact median of all variables. Values of 0 indicate that the location has at least one environmental covariate that is at the upper or lower end of the range of reference conditions, and values <1 indicate that at least one variable falls above or below the reference conditions. MESS can be used, for example, to indicate the degree to which a model constructed in one time period and/or location must extrapolate when projected to another time period and/or location. +#' +#' @param ref A `data.frame`, `data.table`, a points `GVector`, or "stack" of `GRasters`: This represents the set of "reference" environmental conditions: +#' * `data.frame` or `data.table`: There must be one column per layer in `proj`, and the columns must have the same names as the layers in `proj`. +#' * `GRaster` with one or more layers: Must have the same [names()] as the `GRaster`s in `proj`. Values are assumed to be continuous (not categorical/factors). +#' +#' @param proj A `GRaster` or missing. If a `GRaster`, it must have the same layers as can have with one or more layers as `ref`. Values are assumed to be continuous (not categorical/factors). If missing, then `ref` is used, in which case the output represents the relative difference of each cell from the overall layer median. +#' +#' @param na.rm Logical: If `FALSE` (default), and `ref` is a `data.frame`, `data.table`, or `matrix`, and has `NA`s in it, then the function will likely fail. +#' +#' @returns A `GRaster` "stack". There will be one layer per layer in `ref`, indicating the MESS score for that variable. There will also be a layer named "MESS" which represents the MESS value across all variables (the minimum value of each of the individual MESS rasters). A final layer represents the layer which is most different (has the lowest MESS value). +#' +#' @references Elith, J, Kearney, M, and Phillips, S. 2010. The art of modelling range-shifting species. *Methods in Ecology and Evolution* 1:330-342. \doi{10.1111/j.2041-210X.2010.00036.x} (see especially the Supplement) +#' +#' @example man/examples/ex_multivarEnvSim.r +#' +#' @aliases multivarEnvSim +#' @rdname multivarEnvSim +#' @exportMethod multivarEnvSim +methods::setMethod( + f = "multivarEnvSim", + signature = c(ref = "GRaster", proj = "GRaster"), + definition = function( + ref, + proj + ) { + + lyrs <- nlyr(ref) == nlyr(proj) + names1 <- names(ref) %in% names(proj) + names2 <- names(proj) %in% names(ref) + + if (!all(lyrs, names1, names2)) stop("The `ref` and `proj` set of GRasters must have the same number of layers with the same names.") + + ref <- ref[[names(proj)]] + + medians <- global(ref, "median") + mm <- minmax(ref) + + .locationRestore(proj) + .region(proj) + + .multivarEnvSim(ref = ref, proj = proj, medians = medians, mm = mm) + + } # EOF +) + +#' @aliases multivarEnvSim +#' @rdname multivarEnvSim +#' @exportMethod multivarEnvSim +methods::setMethod( + f = "multivarEnvSim", + signature = c(ref = "GRaster", proj = "missing"), + definition = function(ref, proj) multivarEnvSim(ref = ref, proj = ref) +) + +#' @aliases multivarEnvSim +#' @rdname multivarEnvSim +#' @exportMethod multivarEnvSim +methods::setMethod( + f = "multivarEnvSim", + signature = c(ref = "data.frame", proj = "GRaster"), + definition = function(ref, proj, na.rm = FALSE) { + + names2 <- names(proj) %in% names(ref) + if (!all(names2)) stop("Not all layer names in `proj` appear in `ref.") + + .locationRestore(proj) + .region(proj) + + ref <- ref[ , names(proj), drop = FALSE] + + medians <- matrix(apply(ref, 2, "median", na.rm = na.rm), ncol = 1) + rownames(medians) <- colnames(ref) + colnames(medians) <- "median" + + mins <- apply(ref, 2, "min", na.rm = na.rm) + maxs <- apply(ref, 2, "max", na.rm = na.rm) + + mm <- matrix(c(mins, maxs), nrow = 2, byrow = TRUE) + rownames(mm) <- c("min", "max") + colnames(mm) <- names(ref) + + .multivarEnvSim(ref = ref, proj = proj, medians = medians, mm = mm) + + } # EOF +) + +#' @aliases multivarEnvSim +#' @rdname multivarEnvSim +#' @exportMethod multivarEnvSim +methods::setMethod( + f = "multivarEnvSim", + signature = c(ref = "data.table", proj = "GRaster"), + definition = function(ref, proj, na.rm = FALSE) { + + names2 <- names(proj) %in% names(ref) + if (!all(names2)) stop("Not all layer names in `proj` appear in `ref.") + + .locationRestore(proj) + .region(proj) + + cols <- names(proj) + ref <- ref[ , ..cols] + + medians <- matrix(apply(ref, 2, "median", na.rm = na.rm), ncol = 1) + rownames(medians) <- colnames(ref) + colnames(medians) <- "median" + + mins <- apply(ref, 2, "min", na.rm = na.rm) + maxs <- apply(ref, 2, "max", na.rm = na.rm) + + mm <- matrix(c(mins, maxs), nrow = 2, byrow = TRUE) + rownames(mm) <- c("min", "max") + colnames(mm) <- names(ref) + + .multivarEnvSim(ref = ref, proj = proj, medians = medians, mm = mm) + + } # EOF +) + +#' @aliases multivarEnvSim +#' @rdname multivarEnvSim +#' @exportMethod multivarEnvSim +methods::setMethod( + f = "multivarEnvSim", + signature = c(ref = "matrix", proj = "GRaster"), + definition = function(ref, proj, na.rm = FALSE) { + + ref <- data.table::as.data.table(ref) + multivarEnvSim(ref = ref, proj = proj, na.rm = na.rm) + + } # EOF +) + +# Hidden function for multivariate environmental similarity surface (MESS) +# +# ref `GRaster`, `data.frame`, `data.table`, or `matrix` +# proj `GRaster` +# medians Numeric: Vector of median values of `ref` +# mm Numeric matrix of minium/maximum values of `ref`. Top rows is miniums and bottom is maximums. Columns must have same names as `ref`. +.multivarEnvSim <- function(ref, proj, medians, mm) { + + ### MESS values for each variable + nLayers <- nlyr(proj) + srcs <- .makeSourceName("mess_r_mapcalc", "raster", nLayers) + for (i in seq_len(nLayers)) { + + layer <- names(proj)[i] + ySrc <- sources(proj)[i] + + thisMedian <- medians[layer, "median"] + thisMin <- mm["min", layer] + thisMax <- mm["max", layer] + + medianToMax <- thisMax - thisMedian + medianToMin <- thisMedian - thisMin + + ex <- paste0(srcs[i], " = if(", ySrc," >= ", thisMedian, ", 1 - ((", ySrc, " - ", thisMedian, ") / ", medianToMax, "), 1 - ((", thisMedian, " - ", ySrc, ") / ", medianToMin, "))") + + rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + + } + + ### MESS values across all variables + srcOverall <- .makeSourceName("mess_r_mapcalc", "raster") + ex <- paste0(srcOverall, " = min(", paste(srcs, collapse = ","),")") + rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + + ### most different variable + srcMostDiffFrom0 <- .makeSourceName("mess_r_series", "raster") + rgrass::execGRASS( + cmd = "r.series", + input = paste(srcs, collapse=","), + output = srcMostDiffFrom0, + method = "min_raster", + nprocs = faster("cores"), + memory = faster("memory"), + flags = c(.quiet(), "overwrite") + ) + + # add 1 bc "r.series::min_raster" returns 0 for the first raster + srcMostDiffFrom1 <- .makeSourceName("mess_r_mapcalc", "raster") + ex <- paste0(srcMostDiffFrom1, " = int(", srcMostDiffFrom0, " + 1)") + rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + + mostDiffLevels <- data.table::data.table(value = 1L:nLayers, layer = names(proj)) + levs <- vector(mode = "list", length = nLayers + 2) + levs[[length(levs)]] <- mostDiffLevels + + srcsAll <- c(srcs, srcOverall, srcMostDiffFrom1) + outNames <- c(names(proj), "MESS", "mostDifferent") + .makeGRaster(srcsAll, names = outNames, levels = levs) + + +} diff --git a/R/neighborhoodMatrix.r b/R/neighborhoodMatrix.r new file mode 100644 index 00000000..d422d987 --- /dev/null +++ b/R/neighborhoodMatrix.r @@ -0,0 +1,64 @@ +#' Neighborhood matrix from a polygons GVector +#' +#' @description This function returns a neighborhood matrix from a polygons `GVector`, which represents which geometries touch one another. It is useful for implementing geostatistical analyses that require indicators about which area features are next to one another. +#' +#' Polygons must share more than one point for them to be considered a neighbors (i.e., same as `spdep::poly2nb(x, queen = FALSE)`). +#' +#' This function needs the **GRASS** addon `v.neighborhoodmatrix`. If it is not installed, it will try to install it. +#' +#' @param x A polygons `GVector. +#' +#' @returns A `list`. Each element represents a polygon. If an element is empty, it has no neighbors. Otherwise, it is a vector of integers, which represent the indices of the polygon(s) to which it is a neighbor. +#' +#' @example man/examples/ex_neighborhoodMatrix.r +#' +#' @aliases neighborhoodMatrix +#' @rdname neighborhoodMatrix +#' @exportMethod neighborhoodMatrix +methods::setMethod( + f = "neighborhoodMatrix", + signature = c(x = "GVector"), + definition = function(x) { + + if (geomtype(x) != "polygons") stop("The input must be a GVector representing polygons.") + + .addons('v.neighborhoodmatrix') + + neighs <- rgrass::execGRASS( + cmd = "v.neighborhoodmatrix", + input = sources(x), + separator = 'pipe', + flags = c(.quiet(), "b"), + intern = TRUE + ) + + out <- vector(mode = "list", length = ngeom(x)) + for (i in seq_along(out)) out[[i]] <- numeric() + + neighs <- strsplit(neighs, split = "\\|") + neighs <- lapply(neighs, as.integer) + + for (i in seq_along(neighs)) { + + first <- neighs[[i]][1L] + remainder <- neighs[[i]][2L:length(neighs[[i]])] + + remainder <- remainder[remainder != first] + + out[[first]] <- c(out[[first]], remainder) + + } + out + + + } # EOF +) + +#' @aliases neighbourhoodMatrix +#' @rdname neighborhoodMatrix +#' @exportMethod neighbourhoodMatrix +methods::setMethod( + f = "neighbourhoodMatrix", + signature = c(x = "GVector"), + definition = function(x) neighborhoodMatrix(x) +) diff --git a/R/princomp.r b/R/princomp.r index a51486f4..f9fed336 100644 --- a/R/princomp.r +++ b/R/princomp.r @@ -125,7 +125,7 @@ methods::setMethod( #' #' @returns An object of class `prcomp`. #' -#' @seealso [princomp()], [terra::princomp()], module `i.pca` in **GRASS** +#' @seealso [princomp()], [terra::princomp()], tool `i.pca` in **GRASS** #' #' @example man/examples/ex_princomp.r #' diff --git a/R/project.r b/R/project.r index 5a915acc..ab2a0d2e 100644 --- a/R/project.r +++ b/R/project.r @@ -37,7 +37,7 @@ #' #' @param verbose Logical (for projecting `GRaster`s only): If `TRUE`, display progress. Default is `FALSE`. #' -#' @details When projecting a raster, the "fallback" methods in **GRASS** module `r.import` are actually used, even though the `method` argument takes the strings specifying non-fallback methods. See the manual page for the `r.import` **GRASS** module. +#' @details When projecting a raster, the "fallback" methods in **GRASS** tool `r.import` are actually used, even though the `method` argument takes the strings specifying non-fallback methods. See the manual page for the `r.import` **GRASS** tool. #' #' @returns A `GRaster` or `GVector`. #' diff --git a/R/rSpatialDepRast.r b/R/rSpatialDepRast.r index 7e30cd39..cc08b4e7 100644 --- a/R/rSpatialDepRast.r +++ b/R/rSpatialDepRast.r @@ -1,6 +1,6 @@ #' Create a random raster with or without spatial dependence #' -#' @description `rSpatialDepRast()` creates a raster with random values in cells. Across the raster, values are approximately normally distributed, though a raster with a "true" normal distribution can be made with [rnormRast()]. Spatial dependence can be introduced, though all together the values will still be approximately normally distributed. +#' @description `rSpatialDepRast()` creates a raster with random values in cells. Across the raster, values are approximately normally distributed, though a raster with a "true" normal distribution can be made with [rNormRast()]. Spatial dependence can be introduced, though all together the values will still be approximately normally distributed. #' #' @param x A `GRaster`: The output will have the same extent and dimensions as this raster. #' @@ -20,7 +20,7 @@ #' #' @example man/examples/ex_randRast.r #' -#' @seealso [rnormRast()], [fractalRast()], [runifRast()], **GRASS** manual page for module `r.random.surface` (see `grassHelp("r.random.surface")`) +#' @seealso [rNormRast()], [fractalRast()], [rUnifRast()], [rWalkRast()], **GRASS** manual page for tool `r.random.surface` (see `grassHelp("r.random.surface")`) #' #' @aliases rSpatialDepRast #' @rdname rSpatialDepRast diff --git a/R/rWalkRast.r b/R/rWalkRast.r new file mode 100644 index 00000000..586534ae --- /dev/null +++ b/R/rWalkRast.r @@ -0,0 +1,76 @@ +#' Create raster representing one or more random walks +#' +#' This function creates a raster where the cell values represent the number of times one or more random "walkers" traverse the cell. If you simulate multiple random walkers, you can do computation in parallel, which can be controlled by allowing **fasterRaster** to use multiple cores and more memory using the "cores" and "memory" arguments in the [faster()] function. +#' +#' This function needs the **GRASS** addon `r.random.walk`. If it is not installed, it will try to install it.#' +#' @param x A `GRaster` to serve as a template. +#' +#' @param n Numeric: Number of walkers. Default is 1. +#' +#' @param steps Numeric: Number of steps taken by each walker. Default is 100000. +#' +#' @param directions Either 4 or 8: Directions in which a walker can turn at any point. If 4, then walks are confined to north/south/east/west directions (Rook's case). If 8, then the cardinal and subcardinal directions are allowed (Queen's case). +#' +#' @param avoid Logical: If `FALSE` (default), then walkers can traverse their own walks. If `TRUE`, walkers avoid their own trails. A self-avoiding random walk can take much longer to compute. +#' +#' @param sameStart Logical: If `FALSE` (default), walkers can begin anywhere. If `TRUE`, then walkers start from the same place. +#' +#' @param seed Integer or `NULL` (default): If `NULL`, then a random seed is generated by the function. If numeric, results will be deterministic. In either case, the value will be rounded to the nearest integer. +#' +#' @param check Logical: If `TRUE` (default), function will check to see if the addon `r.random.walk` has been installed. If it has not, it will attempt to install it. +#' +#' @returns A `GRaster` with cell values representing the number of times one or more walkers traversed the cell. +#' +#' @seealso [rNormRast()], [rUnifRast()], [rSpatialDepRast()], [fractalRast()] + +#' @example man/examples/ex_randRast.r +#' +#' @aliases rWalkRast +#' @rdname rWalkRast +#' @exportMethod rWalkRast +methods::setMethod( + f = "rWalkRast", + signature = c(x = "GRaster"), + function(x, n = 1, steps = 100000, directions = 8, avoid = FALSE, sameStart = FALSE, seed = NULL, check = TRUE) { + + if (!(directions %in% c(4, 8))) stop("The `directions` argument must be 4 or 8.") + directions <- as.character(directions) + + if (!is.null(seed)) seed <- round(seed) + + if (check) .addons("r.random.walk") + + .locationRestore(x) + .region(x) + + src <- .makeSourceName("rRandWalk_r_random_walk", "raster") + args <- list( + cmd = "r.random.walk", + output = src, + steps = steps, + directions = directions, + memory = faster("memory"), + nprocs = faster("cores"), + nwalkers = n, + flags = c(.quiet(), "overwrite") + ) + + if (!is.null(seed)) { + args <- c(args, seed = seed) + } else if (is.null(seed)) { + args$flags <- c(args$flags, "s") + } + if (avoid) args$flags <- c(args$flags, "a") + if (sameStart) args$flags <- c(args$flags, "t") + + do.call(rgrass::execGRASS, args = args) + + # srcIn <- src + # src <- .makeSourceName("rRandWalk_r_mapcalc", "raster") + # ex <- paste0(src, " = int(", srcIn, ")") + # rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + + .makeGRaster(src, "randomWalk") + + } # EOF +) diff --git a/R/rasterize.r b/R/rasterize.r index f6489792..5710b17d 100644 --- a/R/rasterize.r +++ b/R/rasterize.r @@ -16,7 +16,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::rasterize()], **GRASS** module `v.to.rast` (see `grassHelp("v.to.rast")`) +#' @seealso [terra::rasterize()], **GRASS** tool `v.to.rast` (see `grassHelp("v.to.rast")`) #' #' @example man/examples/ex_rasterize.r #' diff --git a/R/rnormRast.r b/R/rnormRast.r index d2e76aed..aa92a2e3 100644 --- a/R/rnormRast.r +++ b/R/rnormRast.r @@ -1,6 +1,6 @@ #' Create a raster with random values drawn from a normal distribution #' -#' @description `rnormRast()` creates a raster with values drawn from a normal distribution. +#' @description `rNormRast()` creates a raster with values drawn from a normal distribution. #' #' @param x A `GRaster`: The output will have the same extent and dimensions as this raster. #' @@ -14,13 +14,13 @@ #' #' @example man/examples/ex_randRast.r #' -#' @seealso [rSpatialDepRast()], [fractalRast()], [runifRast()], **GRASS** manual page for module `r.random.surface` (see `grassHelp("r.random.surface")`) +#' @seealso [rSpatialDepRast()], [fractalRast()], [rUnifRast()], [rWalkRast()], **GRASS** manual page for tool `r.random.surface` (see `grassHelp("r.random.surface")`) #' -#' @aliases rnormRast -#' @rdname rnormRast -#' @exportMethod rnormRast +#' @aliases rNormRast +#' @rdname rNormRast +#' @exportMethod rNormRast methods::setMethod( - f = "rnormRast", + f = "rNormRast", signature = c(x = "GRaster"), function(x, n = 1, diff --git a/R/ruggedness.r b/R/ruggedness.r index 60523c96..ae901491 100644 --- a/R/ruggedness.r +++ b/R/ruggedness.r @@ -1,8 +1,12 @@ #' Terrain ruggedness index #' -#' @description For a given focal grid cell, the terrain ruggedness index (TRI) is calculated by taking the square root of the average of the squared difference between the focal cell's elevation and the elevations of the 8 surrounding cells, or \deqn{\sqrt(\sum_{i = 1}^{8}(m_i - m_0)^2 / 8)} where \eqn{m_0} is the elevation of the focal cell and \eqn{m_i} is the elevation of the *i*th grid cell. +#' @description For a given focal grid cell, the terrain ruggedness index (TRI) is calculated by taking the square root of the average of the squared difference between the focal cell's elevation and the elevations of the 8 surrounding cells, or \deqn{\sqrt(\sum_{i = 1}^{8}(m_i - m_0)^2 / 8)} where \eqn{m_0} is the elevation of the focal cell and \eqn{m_i} is the elevation of the *i*th grid cell. Areas that are entirely flat will have a value of `NA` assigned to them. +#' +#' By default, TRI is calculated for a 3x3 moving window around each focal cell. However, you can use a larger-sized window. In this case, the window size must be an odd number >= 3, and you must have the `r.tri` **GRASS** addon installed. If it is not installed, the function will try to install it. #' #' @param x A `GRaster`. +#' @param size Integer (default is 3): Size of the moving window. Must be an odd integer >= 3. +#' @param exponent Numeric >= 0 and <= 4. Used to reduce the influence of cells farther from the focal cell (larger areas can yield noisier results if the exponent small). All cells are weighted equally when `exponent = 0`. #' #' @returns A `GRaster`. #' @@ -18,7 +22,11 @@ methods::setMethod( f = "ruggedness", signature = c(x = "GRaster"), - function(x) { + function(x, size = 3, exponent = 0) { + + if (size %% 2 != 1) stop("Argument `size` must be an odd integer >= 3.") + if (exponent < 0 | exponent > 4) stop("Argument `exponent` must in the range [0, 4].") + if (size > 3) .addons("r.tri") .locationRestore(x) .region(x) @@ -27,17 +35,33 @@ methods::setMethod( srcs <- .makeSourceName("terrainRuggednessIndex_r_mapcalc", "raster", n = nLayers) for (i in seq_len(nLayers)) { - ex <- paste0(srcs[i], " = sqrt((", - "(", sources(x)[i], "[-1, -1] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[-1, 0] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[-1, 1] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[0, -1] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[0, 1] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[1, -1] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[1, 0] - ", sources(x), ")^2 + ", - "(", sources(x)[i], "[1, 1] - ", sources(x), ")^2) / 8)") + if (size == 3) { + + ex <- paste0(srcs[i], " = sqrt((", + "(", sources(x)[i], "[-1, -1] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[-1, 0] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[-1, 1] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[0, -1] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[0, 1] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[1, -1] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[1, 0] - ", sources(x), ")^2 + ", + "(", sources(x)[i], "[1, 1] - ", sources(x), ")^2) / 8)") + + rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + + } else { + + rgrass::execGRASS( + cmd = "r.tri", + input = sources(x)[i], + output = srcs[i], + size = size, + exponent = exponent, + # processes = faster("cores"), # does not create raster + flags = c(.quiet(), "overwrite") + ) - rgrass::execGRASS("r.mapcalc", expression = ex, flags = c(.quiet(), "overwrite")) + } } # next layer .makeGRaster(srcs, names = paste0(names(x), "_TRI")) diff --git a/R/runifRast.r b/R/runifRast.r index 5a5823f3..c2119499 100644 --- a/R/runifRast.r +++ b/R/runifRast.r @@ -1,6 +1,6 @@ #' Create a raster with random values drawn from a uniform distribution #' -#' @description `runifRast()` creates a raster with values drawn from a uniform (flat) distribution. +#' @description `rUnifRast()` creates a raster with values drawn from a uniform (flat) distribution. #' #' @param x A `GRaster`. The output will have the same extent and dimensions as this raster. #' @@ -14,13 +14,13 @@ #' #' @example man/examples/ex_randRast.r #' -#' @seealso [rnormRast()], [rSpatialDepRast()], [fractalRast()], **GRASS** manual page for module `r.random.surface` (see `grassHelp("r.random.surface")`) +#' @seealso [rNormRast()], [rSpatialDepRast()], [fractalRast()], [rWalkRast()], **GRASS** manual page for tool `r.random.surface` (see `grassHelp("r.random.surface")`) #' -#' @aliases runifRast -#' @rdname runifRast -#' @exportMethod runifRast +#' @aliases rUnifRast +#' @rdname rUnifRast +#' @exportMethod rUnifRast methods::setMethod( - f = "runifRast", + f = "rUnifRast", signature = c(x = "GRaster"), function( x, diff --git a/R/sampleRast.r b/R/sampleRast.r index f16d319e..618c50d3 100644 --- a/R/sampleRast.r +++ b/R/sampleRast.r @@ -18,7 +18,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [spatSample()]; [terra::spatSample()], module `r.random` in **GRASS** +#' @seealso [spatSample()]; [terra::spatSample()], tool `r.random` in **GRASS** #' #' @example man/examples/ex_sampleRast_spatSample.r #' diff --git a/R/show_print.r b/R/show_print.r index c2a3744e..ac997455 100644 --- a/R/show_print.r +++ b/R/show_print.r @@ -333,7 +333,7 @@ methods::setMethod( # maximum number of fields to show maxFieldsToShow <- 8L - maxColWidth <- 15L + maxColWidth <- 17L maxDigits <- 5L debug <- faster("debug") diff --git a/R/simplifyGeom.r b/R/simplifyGeom.r index e1c1b396..921318cd 100644 --- a/R/simplifyGeom.r +++ b/R/simplifyGeom.r @@ -15,7 +15,7 @@ #' #' @param prop Positive value between 0 and 1: Proportion of points that will be retained for each geometry when the Douglas-Peucker algorithm with reduction is applied (ignored otherwise). Default is 0.5 (retain 50% of vertices). #' -#' @seealso [smoothGeom()], [geometry cleaning][breakPolys], [terra::simplifyGeom()], **GRASS** manual page for module `v.generalize` (see `grassHelp("v.generalize")`) +#' @seealso [smoothGeom()], [geometry cleaning][breakPolys], [terra::simplifyGeom()], **GRASS** manual page for tool `v.generalize` (see `grassHelp("v.generalize")`) #' #' @returns A `GVector`. #' diff --git a/R/smoothGeom.r b/R/smoothGeom.r index b1baeac1..e830fd33 100644 --- a/R/smoothGeom.r +++ b/R/smoothGeom.r @@ -13,7 +13,7 @@ #' #' @param angle Numeric > 0: Maximum angle for the Hermite algorithm. Default is 3. #' -#' @seealso [simplifyGeom()], [terra::simplifyGeom()], [geometry cleaning][breakPolys], **GRASS** manual page for module `v.generalize` (see `grassHelp("v.generalize")`) +#' @seealso [simplifyGeom()], [terra::simplifyGeom()], [geometry cleaning][breakPolys], **GRASS** manual page for tool `v.generalize` (see `grassHelp("v.generalize")`) #' #' @returns A `GVector`. #' diff --git a/R/spatSample.r b/R/spatSample.r index 3bd1ff5d..d9eaf45c 100644 --- a/R/spatSample.r +++ b/R/spatSample.r @@ -26,7 +26,7 @@ #' #' @returns A `data.frame`, `data.table`, or `GVector`. #' -#' @seealso [sampleRast()], [terra::spatSample()], module `v.random` in **GRASS** +#' @seealso [sampleRast()], [terra::spatSample()], tool `v.random` in **GRASS** (see `grassHelp("v.random")`) #' #' @example man/examples/ex_sampleRast_spatSample.r #' @@ -267,6 +267,7 @@ methods::setMethod( # args$flags <- c(args$flags, "b") ### do not create topology... problems? YES! do.call(rgrass::execGRASS, args = args) + ### not loacting by stratum } else { if (verbose | faster("verbose")) omnibus::say("Placing points...") @@ -282,7 +283,6 @@ methods::setMethod( if (!xy & !(values | cats)) args$flags <- c(args$flags, "b") if (!is.null(seed)) args$seed <- round(seed) - do.call(rgrass::execGRASS, args = args) } diff --git a/R/streams.r b/R/streams.r index 4e2dd226..5279183d 100644 --- a/R/streams.r +++ b/R/streams.r @@ -1,6 +1,6 @@ #' Create stream network #' -#' @description This function estimates the course of streams and rivers from an elevation raster. It is based on the **GRASS** module `r.stream.extract`, where more details can be found (see `grassHelp("r.stream.extract")`) +#' @description This function estimates the course of streams and rivers from an elevation raster. It is based on the **GRASS** tool `r.stream.extract`, where more details can be found (see `grassHelp("r.stream.extract")`) #' #' @param x A `GRaster` representing elevation. #' @@ -20,7 +20,7 @@ #' #' @example man/examples/ex_streams.r #' -#' @seealso [flow()], [flowPath()], **GRASS** manual for module `r.stream.extract` (see `grassHelp("r.stream.extract")`) +#' @seealso [flow()], [flowPath()], **GRASS** manual for tool `r.stream.extract` (see `grassHelp("r.stream.extract")`) #' #' @aliases streams #' @rdname streams diff --git a/R/stretch.r b/R/stretch.r index 2e361107..425687e2 100644 --- a/R/stretch.r +++ b/R/stretch.r @@ -12,7 +12,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::stretch()] and module `r.rescale` in **GRASS** (not used on this function) +#' @seealso [terra::stretch()] and tool `r.rescale` in **GRASS** (not used on this function) #' #' @example man/examples/ex_stretch.r #' diff --git a/R/subset_single_bracket.r b/R/subset_single_bracket.r index f2a30e22..01756314 100644 --- a/R/subset_single_bracket.r +++ b/R/subset_single_bracket.r @@ -39,6 +39,16 @@ methods::setMethod( out <- x } else if (!missing(i)) { + if (nrow(x) > 0 & ((is.numeric(i) | is.integer(i)) & any(i != order(i)))) { + + .message( + msg = "subset_square_bracket", + message = +"The GVector returned by `[` (subset_single_bracket) may have the order of items in\n its data table changed from the order they appear in the index used to select features.\n For example, if you use `vector[3:1]`, the results will be as per`vector[1:3]`. If this\n message appeared after you called a function other than `[`, you can probably ignore it." + ) + + } + if (is.logical(i)) { if (length(i) < nGeoms) i <- rep(i, length.out = nGeoms) i <- which(i) @@ -46,7 +56,7 @@ methods::setMethod( if (any(i > 0L) & any(i < 0L)) stop("Cannot mix positive and negative indices.") - # negative indices + # negative indices... removing features if (all(i < 0L)) { reverseRowSelect <- TRUE @@ -56,11 +66,12 @@ methods::setMethod( removeAll <- length(i) == 0L } else { + # positive indices... keeping features reverseRowSelect <- removeAll <- FALSE } if (any(i > nGeoms) | any(i == 0L)) stop("Index out of bounds.") - i <- sort(i) + i <- sort(i) # NB MUST have this, or data table will be mis-matched to features!!!!! if (removeAll) { out <- NULL # removed all @@ -167,7 +178,8 @@ methods::setMethod( input = sources(x), output = src, type = gtype, - flags = c(.quiet(), "overwrite") + # flags = c(.quiet(), "overwrite") + flags = c(.quiet(), "overwrite", "t") # "t" ==> Do not copy attributes ) if (gtype == "point") { @@ -236,6 +248,7 @@ methods::setMethod( # select columns if (missing(j)) { + # not removing all columns removeAllCols <- FALSE } else { diff --git a/R/sun.r b/R/sun.r index b8de7b3c..32381211 100644 --- a/R/sun.r +++ b/R/sun.r @@ -1,6 +1,6 @@ #' Solar radiance and irradiance #' -#' The `sun()` function calculates beam (direct), diffuse and ground reflected solar irradiation for a given day and set of topographic and atmospheric conditions. The function relies on the **GRASS** module `r.sun`, the manual page for which contains a detailed explanation (see `grassHelp("r.sun")`) +#' The `sun()` function calculates beam (direct), diffuse and ground reflected solar irradiation for a given day and set of topographic and atmospheric conditions. The function relies on the **GRASS** tool `r.sun`, the manual page for which contains a detailed explanation (see `grassHelp("r.sun")`) #' #' @param elevation A `GRaster` with values representing elevation (typically in meters). #' @@ -18,7 +18,7 @@ #' #' @param albedo A `GRaster` or a numeric value: This is either a raster with values of ground albedo or a numeric value (in which case albedo is assumed to be the same everywhere). Albedo is unit-less, and the default value is 0.2. #' -#' @param linke A `GRaster` or a numeric value: This is either a raster with values of the Linke atmospheric turbidity coefficient or a numeric value (in which case the same value is assumed for all locations). The Linke coefficient is unit-less. The default value is 3, but see also the **GRASS** manual page for module `r.sun` (`grassHelp("r.sun")`). +#' @param linke A `GRaster` or a numeric value: This is either a raster with values of the Linke atmospheric turbidity coefficient or a numeric value (in which case the same value is assumed for all locations). The Linke coefficient is unit-less. The default value is 3, but see also the **GRASS** manual page for tool `r.sun` (`grassHelp("r.sun")`). #' #' @param day Positive integer between 1 to 365, inclusive: Day of year for which to calculate ir/radiation. Default is 1 (January 1st). #' @@ -32,17 +32,17 @@ #' #' @param npartitions Positive numeric. Number of chunks in which to read input files. Default is 1. #' -#' @param beam_rad Logical: If `TRUE` (default), generate a raster with beam irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** module). +#' @param beam_rad Logical: If `TRUE` (default), generate a raster with beam irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** tool). #' #' @param diff_rad Logical: If `TRUE` (default), generate a raster representing irradiation in Wh / m^2 /day #' -#' @param refl_rad Logical: If `TRUE` (default), generate a raster with ground-reflected irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** module). +#' @param refl_rad Logical: If `TRUE` (default), generate a raster with ground-reflected irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** tool). #' -#' @param glob_rad Logical:. If `TRUE` (default), generate a raster with total irradiance/irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** module). +#' @param glob_rad Logical:. If `TRUE` (default), generate a raster with total irradiance/irradiation with units of Wh / m^2 / day ("mode 2" of the `r.sun` **GRASS** tool). #' -#' @param insol_time Logical: If `TRUE` (default), generate a raster with total insolation time in hours ("mode 2" of the `r.sun` **GRASS** module). +#' @param insol_time Logical: If `TRUE` (default), generate a raster with total insolation time in hours ("mode 2" of the `r.sun` **GRASS** tool). #' -#' @param lowMemory Logical: If `TRUE`, use the low-memory version of the `r.sun` **GRASS** module. The default is `FALSE`. +#' @param lowMemory Logical: If `TRUE`, use the low-memory version of the `r.sun` **GRASS** tool. The default is `FALSE`. #' #' @returns A raster or raster stack stack with the same extent, resolution, and coordinate reference system as `elevation`. Assuming all possible rasters are generated they represent: #' * `beam_rad`: Beam radiation (Watt-hours/m2/day) @@ -51,7 +51,7 @@ #' * `glob_rad`: Global radiation (Watt-hours/m2/day) #' * `insol_time`: Insolation duration (hours) #' -#' @seealso [terrain()], [horizonHeight()], **GRASS** manual page for module `r.sun` (see `grassHelp("r.sun")`) +#' @seealso [terrain()], [horizonHeight()], **GRASS** manual page for tool `r.sun` (see `grassHelp("r.sun")`) #' #' @example man/examples/ex_sun.r #' diff --git a/R/terrain.r b/R/terrain.r index c0b2a2cf..fb5f6f13 100644 --- a/R/terrain.r +++ b/R/terrain.r @@ -24,7 +24,7 @@ #' #' @returns A `GRaster` with one or more layers. #' -#' @seealso [terra::terrain()], [ruggedness()], [wetness()], [geomorphons()], module `r.slope.aspect` in **GRASS** +#' @seealso [terra::terrain()], [ruggedness()], [wetness()], [geomorphons()], tool `r.slope.aspect` in **GRASS** #' #' @example man/examples/ex_terrain.r #' diff --git a/R/thinLines.r b/R/thinLines.r index b31338f5..ca96a7f4 100644 --- a/R/thinLines.r +++ b/R/thinLines.r @@ -8,7 +8,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [as.lines()], **GRASS** manual page for module `r.thin` (see `grassHelp("r.thin")`) +#' @seealso [as.lines()], **GRASS** manual page for tool `r.thin` (see `grassHelp("r.thin")`) #' #' @example man/examples/ex_asLines.r #' diff --git a/R/trim.r b/R/trim.r index 358fa97b..8e1ff4c6 100644 --- a/R/trim.r +++ b/R/trim.r @@ -10,7 +10,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terra::trim()], [extend()], and **GRASS** module `g.region` +#' @seealso [terra::trim()], [extend()], and **GRASS** tool `g.region` #' #' @example man/examples/ex_trim.r #' diff --git a/R/vegIndex.r b/R/vegIndex.r index 073ec781..ea303f25 100644 --- a/R/vegIndex.r +++ b/R/vegIndex.r @@ -21,7 +21,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso **GRASS** manual page for module `i.vi` (see `grassHelp("i.vi")`) +#' @seealso **GRASS** manual page for tool `i.vi` (see `grassHelp("i.vi")`) #' #' @example man/examples/ex_vegIndex.r #' diff --git a/R/voronoi.r b/R/voronoi.r index ca08349a..1badcb84 100644 --- a/R/voronoi.r +++ b/R/voronoi.r @@ -7,7 +7,7 @@ #' #' @returns A `GVector`. #' -#' @seealso [terra::voronoi()], [sf::st_voronoi()], module `v.voronoi` in **GRASS** +#' @seealso [terra::voronoi()], [sf::st_voronoi()], tool `v.voronoi` in **GRASS** #' #' @example man/examples/ex_delaunay_voronoi.r #' diff --git a/R/wetness.r b/R/wetness.r index 3baa3ca6..eb9c84d8 100644 --- a/R/wetness.r +++ b/R/wetness.r @@ -6,7 +6,7 @@ #' #' @returns A `GRaster`. #' -#' @seealso [terrain()], [ruggedness()], [geomorphons()], **GRASS** manual for module `r.topidx` (see `grassHelp("r.topidx")`) +#' @seealso [terrain()], [ruggedness()], [geomorphons()], **GRASS** manual for tool `r.topidx` (see `grassHelp("r.topidx")`) #' #' @example man/examples/ex_ruggedness_wetness.r #' diff --git a/R/workDir.r b/R/workDir.r index 2b791f64..7cb54387 100644 --- a/R/workDir.r +++ b/R/workDir.r @@ -2,7 +2,7 @@ #' #' @description This function returns the working directory of a `GLocation` object. #' -#' @param x A `GLocation` object. +#' @param x A `GLocation` object or missing. If an object, returns the working folder in which the object is saved by **GRASS**. If missing, then just returns the working folder (same as `faster("workDir")`). #' #' @returns Character. #' @@ -15,3 +15,13 @@ methods::setMethod( signature = c(x = "GLocation"), function(x) x@workDir ) + +#' @aliases .workDir +#' @rdname workDir +#' @exportMethod .workDir +#' @keywords internal +methods::setMethod( + f = ".workDir", + signature = c(x = "missing"), + function(x) faster("workDir") +) diff --git a/R/writeRaster.r b/R/writeRaster.r index 28abbbd4..809f655f 100644 --- a/R/writeRaster.r +++ b/R/writeRaster.r @@ -3,7 +3,7 @@ #' @description #' This function saves a `GRaster` to disk directly from a **GRASS** session. It is faster than using [rast()], then saving the output of that to disk (because `rast()` actually save the raster to disk, anyway). #' -#' The function will attempt to ascertain the file type to be ascertained from the file extension, but you can specify the format using the `format` argument (see entry for `...`). You can see a list of supported formats by simply using this function with no arguments, as in `writeRaster()`, or by consulting the online help page for the **GRASS** module `r.out.gdal` (see `grassHelp("r.out.gdal")`). Only the `GeoTIFF` file format is guaranteed to work for multi-layered rasters. +#' The function will attempt to ascertain the file type to be ascertained from the file extension, but you can specify the format using the `format` argument (see entry for `...`). You can see a list of supported formats by simply using this function with no arguments, as in `writeRaster()`, or by consulting the online help page for the **GRASS** tool `r.out.gdal` (see `grassHelp("r.out.gdal")`). Only the `GeoTIFF` file format is guaranteed to work for multi-layered rasters. #' #' The function will attempt to optimize the `datatype` argument, but this can take a long time. You can speed this up by setting `datatype` manually. Note that if you are saving a "stack" of `GRaster`s with different `datatype`s, the one with the highest information density will be used (e.g., low-bit integer < high-bit integer < floating-point < double-floating point). This can make rasters with lower datatypes much larger on disk. In these cases, it make be best to save rasters with similar `datatype`s together. #' @@ -45,7 +45,7 @@ #' #' @param ... Additional arguments. These can include: #' * `bigTiff`: Logical: If `TRUE`, and the file format is a GeoTIFF and would be larger than 4 GB (regardless of compression), then the file will be saved in BIGTIFF format. -#' * `format`: Character, indicating file format. This is usually ascertained from the file extension, but in case this fails, it can be stated explicitly. When using other formats, you may have to specify the `createopts` argument, too (see help page for **GRASS** module `r.out.gdal`). Two common formats include: +#' * `format`: Character, indicating file format. This is usually ascertained from the file extension, but in case this fails, it can be stated explicitly. When using other formats, you may have to specify the `createopts` argument, too (see help page for **GRASS** tool `r.out.gdal`). Two common formats include: #' * `"GTiff"` (default): GeoTIFF `filename` ends in `.tif`. #' * `"ASC"`: ASCII `filename` ends in `.asc` #' * Additional arguments to send to **GRASS** modules `r.out.gdal` and `r.out.ascii`. @@ -53,7 +53,7 @@ #' #' @returns A `GRaster` (invisibly). A raster is also saved to disk. #' -#' @seealso [terra::writeRaster()], **GRASS** module `r.out.gdal` (see `grassHelp("r.out.gdal")`) +#' @seealso [terra::writeRaster()], **GRASS** tool `r.out.gdal` (see `grassHelp("r.out.gdal")`) #' #' @example man/examples/ex_writeRaster.r #' diff --git a/R/writeVector.r b/R/writeVector.r index 2153d930..f67d8f63 100644 --- a/R/writeVector.r +++ b/R/writeVector.r @@ -2,7 +2,7 @@ #' #' @description This function saves a `GVector` to disk directly from a **GRASS** session. #' -#' By default, files will be of OGC GeoPackage format (extension "`.gpkg`"), but this can be changed with the `format` argument. You can see a list of supported formats by simply using this function with no arguments, as in `writeVector()`, or by consulting the online help page for **GRASS** module `v.out.ogr` (see `grassHelp("v.out.ogr")`). +#' By default, files will be of OGC GeoPackage format (extension "`.gpkg`"), but this can be changed with the `format` argument. You can see a list of supported formats by simply using this function with no arguments, as in `writeVector()`, or by consulting the online help page for **GRASS** tool `v.out.ogr` (see `grassHelp("v.out.ogr")`). #' #' Note that if the vector has a data table attached and at least one numeric or integer column has an `NA` or `NaN` value, the function will yield a warning like: #' ``` @@ -27,15 +27,15 @@ #' #' @param attachTable Logical: If `TRUE` (default), attach the attribute to table to the vector before saving it. If `FALSE`, the attribute table will not be attached. #' -#' @param ... Additional arguments to send to **GRASS** module `v.out.ogr` (see `grassHelp("v.out.ogr")`). +#' @param ... Additional arguments to send to **GRASS** tool `v.out.ogr` (see `grassHelp("v.out.ogr")`). #' #' @returns Invisibly returns a `GRaster` (the input, `x`). Also saves the vector to disk. #' -#' @seealso [terra::writeVector()], [sf::st_write()], **GRASS** module `v.out.ogr` (see `grassHelp("v.out.ogr")`) +#' @seealso [terra::writeVector()], [sf::st_write()], **GRASS** tool `v.out.ogr` (see `grassHelp("v.out.ogr")`) #' #' @example man/examples/ex_writeVector.r #' -#' @seealso [terra::writeVector()], the **GRASS** module manual page for `v.out.ogr` (see `grassHelp("v.out.ogr")`) +#' @seealso [terra::writeVector()], the **GRASS** tool manual page for `v.out.ogr` (see `grassHelp("v.out.ogr")`) #' #' @aliases writeVector #' @rdname writeVector diff --git a/README.md b/README.md index 5046512c..0b6d4d95 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,11 @@ [![cran version](https://www.r-pkg.org/badges/version/fasterRaster)](https://cran.r-project.org/package=fasterRaster) [![R-CMD-check](https://github.com/adamlilith/fasterRaster/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/adamlilith/fasterRaster/actions/workflows/R-CMD-check.yaml) [![GPLv3 license](https://img.shields.io/badge/License-GPLv3-blue.svg)](http://perso.crans.org/besson/LICENSE.html) -Faster raster processing in `R` using `GRASS GIS` +Faster raster processing in `R` using `GRASS` -fasterRaster website +fasterRaster website -`fasterRaster` is an **R** package designed specifically to handle large-in-memory/large-on-disk spatial rasters and vectors. `fasterRaster` does this using Open Source Geospatial's `GRASS GIS` +`fasterRaster` is an **R** package designed specifically to handle large-in-memory/large-on-disk spatial rasters and vectors. `fasterRaster` does this using Open Source Geospatial's `GRASS` `fasterRaster` was created with five design principles: @@ -16,12 +16,12 @@ Faster raster processing in `R` using `GRASS GIS` * **Familiarity**: If you know how to use `terra`, you basically know how to use `fasterRaster`! That's because most of the functions have the same name and almost the same arguments as `terra` functions. * **Comparability**: To the degree possible, outputs from `fasterRaster` are the same as those from functions in `terra` with the same name. * **Simplicity**: `GRASS` requires users to track things like "locations" or "projects", "mapsets", and "regions" for which there is no comparable analog in the `terra` or `sf` packages. `fasterRaster` handles these behind the scenes so you don't need to. -* **It's R**: The `rgrass` package provides a powerful conduit through which you can run `GRASS` modules from `R`. As such, it provides much more flexibility than `fasterRaster`. However, to use `rgrass`, you need to know what `GRASS` modules you want to use and be familiar with `GRASS` syntax. `fasterRaster` obviates this step but uses `rgrass` as a backend, allowing you to focus on `R` syntax and look up help for functions the normal way you do in `R`. You don't need to know `GRASS`! +* **It's R**: The `rgrass` package provides a powerful conduit through which you can run `GRASS` tools from `R`. As such, it provides much more flexibility than `fasterRaster`. However, to use `rgrass`, you need to know what `GRASS` tools you want to use and be familiar with `GRASS` syntax. `fasterRaster` obviates this step but uses `rgrass` as a backend, allowing you to focus on `R` syntax and look up help for functions the normal way you do in `R`. You don't need to know `GRASS`! -`fasterRaster` makes heavy use of the `rgrass` package by Roger Bivand and others, the `terra` package by Robert Hijmans, the `sf` package by Edzer Pebesma, Roger Bivand, and others, and of course `GRASS GIS`, so is greatly indebted to all of these creators! +`fasterRaster` makes heavy use of the `rgrass` package by Roger Bivand and others, the `terra` package by Robert Hijmans, the `sf` package by Edzer Pebesma, Roger Bivand, and others, and of course `GRASS`, so is greatly indebted to all of these creators! # Vignettes & documentation -**fasterRaster** comes with four user-oriented vignettes, plus a `pkgdown` site with full documentation: +**fasterRaster** comes with four user-oriented vignettes, plus a `pkgdown` site with full documentation: o Getting started (also reproduced below) o Types of `GRaster`s @@ -44,7 +44,7 @@ You can get the latest stable release using: To use `fasterRaster` you must install [GRASS version 8.3+](https://grass.osgeo.org/) on your operating system. **You will need to use the stand-alone installer, not the Open Source Geospatial (OS Geo) installer.** -**Optional**: A few functions in **fasterRaster** require **GRASS** "addon" modules, which do not come bundled with **GRASS**. You do not need to install these addons if you do not use functions that call them. A list of functions that require addons can be seen in the "addons" vignette (in **R**, use `vignette("addons", package = "fasterRaster")`). This vignette also explains how to install addons. +**Optional**: A few functions in **fasterRaster** require **GRASS** "addon" tools, which do not come bundled with **GRASS**. You do not need to install these addons if you do not use functions that call them. A list of functions that require addons can be seen in the "addons" vignette (in **R**, use `vignette("addons", package = "fasterRaster")`). This vignette also explains how to install addons. # An example @@ -185,12 +185,12 @@ Note that the `M1.M2` and `S1.S2` increment independently. For example, if the v * Robert Hijman's [`terra`](https://cran.r-project.org/package=terra) package and Edzer Pebesma's [`sf`](https://cran.r-project.org/package=sf) package are good places to start if you are not familiar with doing GIS in `R`. * Roger Bivand's [`rgrass`](https://cran.r-project.org/package=rgrass) package allows users to call any `GRASS` function with all of its functionality, which in some cases is far beyond what is allowed by `fasterRaster`. -* The [GRASS GIS](https://grass.osgeo.org/) website is authoritative and contains the manual on all the `GRASS` functions used in this package and more. +* The [GRASS](https://grass.osgeo.org/) website is authoritative and contains the manual on all the `GRASS` functions used in this package and more. * The Wiki on [how to run `GRASS` in `R` or `R` in `GRASS`](https://grasswiki.osgeo.org/wiki/R_statistics/rgrass) will help you to become a power-user of `GRASS` in `R`. # Citation A publication is forthcoming! In the meantime, please cite: -Smith, A.B. 2024. `fasterRaster`: Faster raster processing in `R` using `GRASS GIS`. URL: https://cran.r-project.org/package=fasterRaster. +Smith, A.B. 2024. `fasterRaster`: Faster raster processing in `R` using `GRASS`. URL: https://cran.r-project.org/package=fasterRaster. ~ Adam diff --git a/_pkgdown.yml b/_pkgdown.yml index 5973d8db..911e2a36 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -1,5 +1,5 @@ home: - title: Faster Raster and Spatial Vector Processing Using 'GRASS GIS' + title: Faster Raster and Spatial Vector Processing Using 'GRASS' description: Processing of large-in-memory/large-on disk rasters. url: https://github.com/adamlilith/fasterRaster @@ -19,7 +19,6 @@ articles: contents: - GRasters - faster_fasterRaster - - addons - three_d_objects - title: For Developers @@ -40,7 +39,6 @@ reference: - st_as_sf - writeRaster - writeVector - - addons - title: GRaster properties - contents: - crs @@ -156,6 +154,7 @@ reference: - app - c - cellSize + - centroids - classify - clump - combineLevels @@ -177,6 +176,7 @@ reference: - maskNA - match - merge + - multivarEnvSim - names<- - noise - pairs @@ -208,9 +208,10 @@ reference: - fractalRast - init - longlat - - rnormRast + - rNormRast - rSpatialDepRast - - runifRast + - rUnifRast + - rWalkRast - sineRast - title: Terrain and hydrology - contents: @@ -331,6 +332,8 @@ reference: - kernel - missing.cases - names<- + - neighborhoodMatrix + - neighbourhoodMatrix - project - rasterize - rbind @@ -381,13 +384,16 @@ reference: - vect - title: General functions - contents: + - addons - compareGeom - dropRows - grassGUI - grassHelp - grassInfo - grassStarted + - installAddon - mow + - removeAddon - replaceNAs - seqToSQL - update diff --git a/inst/pkgdown.yml b/inst/pkgdown.yml index 9503be36..a0dc858b 100644 --- a/inst/pkgdown.yml +++ b/inst/pkgdown.yml @@ -1,8 +1,7 @@ pandoc: 3.6.2 -pkgdown: 2.1.1 +pkgdown: 2.1.3 pkgdown_sha: ~ articles: - addons: addons.html faster_fasterRaster: faster_fasterRaster.html fasterRaster: fasterRaster.html GRasters: GRasters.html @@ -10,7 +9,7 @@ articles: projects_mapsets: projects_mapsets.html regions: regions.html three_d_objects: three_d_objects.html -last_built: 2025-04-25T13:52Z +last_built: 2025-06-19T21:54Z urls: reference: https://github.com/adamlilith/fasterRaster/reference article: https://github.com/adamlilith/fasterRaster/articles diff --git a/man/add.Rd b/man/add.Rd index 43a410e8..c539ed2a 100644 --- a/man/add.Rd +++ b/man/add.Rd @@ -88,6 +88,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -96,14 +97,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -112,9 +119,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/addons.Rd b/man/addons.Rd index 8e22ba06..904b9bc6 100644 --- a/man/addons.Rd +++ b/man/addons.Rd @@ -2,38 +2,44 @@ % Please edit documentation in R/addons.r \name{addons} \alias{addons} +\alias{installAddon} +\alias{removeAddon} +\alias{.addons} \title{Test if addons directory exists and if an addon is installed} \usage{ -addons(x = NULL, fail = TRUE, verbose = TRUE) +addons(x = NULL) + +installAddon(x, check = TRUE) + +removeAddon(x, check = TRUE) + +.addons(x) } \arguments{ -\item{x}{Either \code{NULL} or a character specifying the name of a \strong{GRASS} addons module. If \code{NULL}, the existence of the \code{addonsDir} (see \code{\link[=faster]{faster()}}) will be tested. If the module name is provided, the existence of the folder and module will be tested. The "\verb{/bin}" subfolder should not be included.} - -\item{fail}{Logical: If \code{TRUE} (default), and the addons folder is not correctly specified, the exit the function with an error. If \code{FALSE}, then \code{NULL} will be returned with a warning.} +\item{x}{Either \code{NULL} or a character specifying the name of a \strong{GRASS} addons tool. If \code{NULL}, a vector of installed addons is returned. If a character vector is provided, a logical vector is returned, one per value in \code{x} that indicates if the respective addon is installed.} -\item{verbose}{Logical: If \code{TRUE} (default), display a message on success or warning (the \code{fail} option always displays a message).} +\item{check}{Logical: If \code{TRUE}, check to see if the addon is available (\code{installAddon()})or if it is installed (\code{removeAddon()}).} } \value{ -Logical. +\code{addons()}: Logical. The other functions invisibly return a logical value indicating if the operation succeeded or not. } \description{ -This function tests to see if the "addons" directory specified using \code{\link[=faster]{faster()}} actually exists, and if a particular \strong{GRASS} \verb{addons module is available. The }addons\verb{folder and module must exists for methods that rely on particular **GRASS**}addons\verb{to work. See}vignette("addons", package = "fasterRaster")`. +These functions handle \strong{GRASS} addons, which are optional tools that can be installed. Most functions in \strong{fasterRaster} rely on "base" \strong{GRASS} tools (not addons), but a few do. +\itemize{ +\item \code{addons()}: Either lists all installed addons or verifies if one or more specific addons are installed. +\item \code{installAddon()}: Installs a \strong{GRASS} addon. An addon typically only needs installed once. You can install an addon, quit and restart \strong{R}, attach \strong{fasterRaster}, and any installed addons can be used without using this function again. +\item \code{removeAddon()}: Delete an installed addon from your system. +} } \examples{ if (grassStarted()) { -# Does the addons folder exist? -ao <- addons(fail = "warning") -if (ao) print("Addons is folder is probably correctly specified.") - -# Does this particular module exist? -addon <- "v.centerpoint" -exten <- addons(addon, fail = FALSE) +# What addons are installed? +addons() -if (exten) print("Extension `v.centerpoints` is installed.") +# Is a specific addon installed? +addons(c("v.centerpoint", "fake.addon")) } } -\seealso{ -\code{vignette("addons", package = "fasterRaster")} -} +\keyword{internal} diff --git a/man/app.Rd b/man/app.Rd index 7660694b..db5cd7f7 100644 --- a/man/app.Rd +++ b/man/app.Rd @@ -23,7 +23,7 @@ appFuns(warn = TRUE) \item The \code{\link[=names]{names()}} of the rasters do not match any of the functions in the \code{appFuns(TRUE)} table. Note that \code{x} and \code{y} are forbidden names :( } -The help page for \strong{GRASS} module \code{r.mapcalc} will be especially helpful. You can see this page using \code{grassHelp("r.mapcalc")}.} +The help page for \strong{GRASS} tool \code{r.mapcalc} will be especially helpful. You can see this page using \code{grassHelp("r.mapcalc")}.} \item{datatype}{Character: This ensures that rasters are treated as a certain type before they are operated on. This is useful when using rasters that have all integer values, which \strong{GRASS} can assume represent integers, even if they are not supposed to. In this case, the output of operations on this raster might be an integer if otherwise not corrected. Partial matching is used, and options include: \itemize{ @@ -126,5 +126,5 @@ print(freqs) } } \seealso{ -\code{\link[terra:app]{terra::app()}}, \code{\link[terra:lapp]{terra::lapp()}}, \code{\link[=subst]{subst()}}, \code{\link[=classify]{classify()}}, and especially the \strong{GRASS} manual page for module \code{r.mapcalc} (see \code{grassHelp("r.mapcalc")}) +\code{\link[terra:app]{terra::app()}}, \code{\link[terra:lapp]{terra::lapp()}}, \code{\link[=subst]{subst()}}, \code{\link[=classify]{classify()}}, and especially the \strong{GRASS} manual page for tool \code{r.mapcalc} (see \code{grassHelp("r.mapcalc")}) } diff --git a/man/as.contour.Rd b/man/as.contour.Rd index c29bd902..22c8e3cd 100644 --- a/man/as.contour.Rd +++ b/man/as.contour.Rd @@ -41,5 +41,5 @@ plot(conts, add = TRUE) } } \seealso{ -\code{\link[terra:contour]{terra::as.contour()}}, \strong{GRASS} manual page for module \code{r.contour} (see \code{grassHelp("r.contour")}) +\code{\link[terra:contour]{terra::as.contour()}}, \strong{GRASS} manual page for tool \code{r.contour} (see \code{grassHelp("r.contour")}) } diff --git a/man/as.lines.Rd b/man/as.lines.Rd index 6df4239b..3f950431 100644 --- a/man/as.lines.Rd +++ b/man/as.lines.Rd @@ -44,5 +44,5 @@ plot(cleanLines, add = TRUE) } } \seealso{ -\code{\link[=as.points]{as.points()}}, \code{\link[=as.polygons]{as.polygons()}}, \code{\link[terra:as.lines]{terra::as.lines()}}, \code{\link[=thinLines]{thinLines()}}, \link[=breakPolys]{geometry cleaning}, and \strong{GRASS} module \code{r.to.vect} +\code{\link[=as.points]{as.points()}}, \code{\link[=as.polygons]{as.polygons()}}, \code{\link[terra:as.lines]{terra::as.lines()}}, \code{\link[=thinLines]{thinLines()}}, \link[=breakPolys]{geometry cleaning}, and \strong{GRASS} tool \code{r.to.vect} } diff --git a/man/as.polygons.Rd b/man/as.polygons.Rd index cb1dc6d9..5a250122 100644 --- a/man/as.polygons.Rd +++ b/man/as.polygons.Rd @@ -42,5 +42,5 @@ plot(rastToPolys) } } \seealso{ -\code{\link[=as.points]{as.points()}}, \code{\link[=as.lines]{as.lines()}}, \code{\link[terra:as.polygons]{terra::as.polygons()}}, \link[=breakPolys]{geometry cleaning}, and \strong{GRASS} module \code{r.to.vect} +\code{\link[=as.points]{as.points()}}, \code{\link[=as.lines]{as.lines()}}, \code{\link[terra:as.polygons]{terra::as.polygons()}}, \link[=breakPolys]{geometry cleaning}, and \strong{GRASS} tool \code{r.to.vect} } diff --git a/man/breakPolys.Rd b/man/breakPolys.Rd index ce5113fb..2881f454 100644 --- a/man/breakPolys.Rd +++ b/man/breakPolys.Rd @@ -155,5 +155,5 @@ legend("bottom", } } \seealso{ -\code{\link[terra:topology]{terra::topology()}}, \code{\link[=fillHoles]{fillHoles()}}, \code{\link[terra:topology]{terra::removeDupNodes()}}, \emph{Details} section in \code{\link[=fast]{fast()}}, \code{\link[=simplifyGeom]{simplifyGeom()}}, \code{\link[=smoothGeom]{smoothGeom()}}, \strong{GRASS} manual page for module \code{v.clean} (see \code{grassHelp("v.clean")}) +\code{\link[terra:topology]{terra::topology()}}, \code{\link[=fillHoles]{fillHoles()}}, \code{\link[terra:topology]{terra::removeDupNodes()}}, \emph{Details} section in \code{\link[=fast]{fast()}}, \code{\link[=simplifyGeom]{simplifyGeom()}}, \code{\link[=smoothGeom]{smoothGeom()}}, \strong{GRASS} manual page for tool \code{v.clean} (see \code{grassHelp("v.clean")}) } diff --git a/man/centroids.Rd b/man/centroids.Rd index bc5306d0..133a0a6d 100644 --- a/man/centroids.Rd +++ b/man/centroids.Rd @@ -3,14 +3,17 @@ \name{centroids,GVector-method} \alias{centroids,GVector-method} \alias{centroids} -\title{Centroid(s) of a vector} +\alias{centroids,GRaster-method} +\title{Centroid(s) of a vector or clumps in a raster} \usage{ -\S4method{centroids}{GVector}(x, method = NULL, fail = TRUE) +\S4method{centroids}{GVector}(x, method = NULL) + +\S4method{centroids}{GRaster}(x) } \arguments{ -\item{x}{A \code{GVector}.} +\item{x}{A \code{GVector} or \code{GRaster}.} -\item{method}{Character or \code{NULL} (default): Method used for calculating centroids. The method of calculation depends on whether the input is a \code{points}, \code{lines}, or \code{polygons} \code{GVector}. If the value is \code{NULL}, then the default method will be chosen, depending on the geometry type of the \code{GVector}: +\item{method}{\code{GVector}s: Character or \code{NULL} (default): Method used for calculating centroids. The method of calculation depends on whether the input is a \code{points}, \code{lines}, or \code{polygons} \code{GVector}. If the value is \code{NULL}, then the default method will be chosen, depending on the geometry type of the \code{GVector}: \itemize{ \item \code{points}: \itemize{ @@ -33,16 +36,14 @@ } Partial matching is used and case is ignored.} - -\item{fail}{Logical: If \code{TRUE} (default), and the addons folder is not correctly specified, the exit the function with an error. If \code{FALSE}, then \code{NULL} will be returned with a warning.} } \value{ -A points \code{GVector}. +If the input is a \code{GVector}, the output will be a "points" \code{GVector}. If the input is a \code{GRaster}, the output will be a "points" \code{GVector} with a table with statistics on each clump. If the input is a \code{GRaster} with more than one layer, the output will be a \code{list} of \code{GVector}s, with one \code{GVector} per layer. } \description{ -This function locates the centroid of each geometry of a \code{GVector}. +This function locates the centroid of each geometry of a \code{GVector}, or the centroid of each "clump" of same-valued cells in an integer/categorical raster (for information on types of \code{GRaster}s, see \code{vignette("GRasters", package = "fasterRaster")}). -\strong{To use this function}, you must a) have correctly specified the \code{addonsDir} option using \code{\link[=faster]{faster()}}, and b) installed the \strong{GRASS} addon \code{v.centerpoint}. See \code{\link[=addons]{addons()}} and \code{vignette("addons", package = "fasterRaster")}. +To use this function with a \code{GVector}, you need the \strong{GRASS} \code{v.centerpoint} addon. To use the function with a \code{GRaster}, you need the addon \code{r.centroids}. In either case, the function will try to install the respective addon (i.e., you need to have an internet connection). Once installed, a tool will not need to be installed again. } \examples{ if (grassStarted()) { @@ -51,78 +52,84 @@ if (grassStarted()) { library(sf) library(terra) -# Points, lines, and polygons -madDypsis <- fastData("madDypsis") -madRivers <- fastData("madRivers") -madCoast4 <- fastData("madCoast4") - -# Convert to GVectors: -dypsis <- fast(madDypsis) -rivers <- fast(madRivers) -coast4 <- fast(madCoast4) +### Points, line, and polygon centroids # Point centroids: -dypMean <- centroids(dypsis, fail = FALSE) -dypMedian <- centroids(dypsis, method = "median", fail = FALSE) -dypPMedian <- centroids(dypsis, method = "pmedian", fail = FALSE) +madDypsis <- fastData("madDypsis") +dypsis <- fast(madDypsis) -if (!is.null(dypMean)) { +dypMean <- centroids(dypsis) +dypMedian <- centroids(dypsis, method = "median") +dypPMedian <- centroids(dypsis, method = "pmedian") plot(dypsis) plot(dypMean, col = "red", add = TRUE) plot(dypMedian, col = "green", pch = 2, add = TRUE) -plot(dypPMedian, col = "orange", pch = 1, add = TRUE) +plot(dypPMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mean", "median", "pmedian"), - col = c("red", "green", "orange"), - pch = c(16, 2, 1), + col = c("red", "green", "blue"), + pch = c(16, 2, 3), xpd = NA ) -} - # Line centroids: -riversMid <- centroids(rivers, fail = FALSE) -riversMean <- centroids(rivers, method = "mean", fail = FALSE) -riversMedian <- centroids(rivers, method = "median", fail = FALSE) +madRivers <- fastData("madRivers") +rivers <- fast(madRivers) -if (!is.null(riversMid)) { +riversMid <- centroids(rivers) +riversMean <- centroids(rivers, method = "mean") +riversMedian <- centroids(rivers, method = "median") plot(rivers) plot(riversMid, col = "red", add = TRUE) plot(riversMean, col = "green", pch = 2, add = TRUE) -plot(riversMedian, col = "orange", pch = 1, add = TRUE) +plot(riversMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mid", "mean", "median"), - col = c("red", "green", "orange"), - pch = c(16, 2, 1), + col = c("red", "green", "blue"), + pch = c(16, 2, 3), xpd = NA ) -} - # Polygon centroids: -coastMean <- centroids(coast4, fail = FALSE) -coastMedian <- centroids(coast4, method = "median", fail = FALSE) -coastBMedian <- centroids(coast4, method = "bmedian", fail = FALSE) +madCoast4 <- fastData("madCoast4") +coast4 <- fast(madCoast4) -if (!is.null(coastMean)) { +coastMean <- centroids(coast4) +coastMedian <- centroids(coast4, method = "median") +coastBMedian <- centroids(coast4, method = "bmedian") plot(coast4) plot(coastMean, col = "red", add = TRUE) plot(coastMedian, col = "green", pch = 2, add = TRUE) -plot(coastBMedian, col = "orange", pch = 1, add = TRUE) +plot(coastBMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mean", "median", "bmedian"), - col = c("red", "green", "orange"), + col = c("red", "green", "blue"), pch = c(16, 2, 1), xpd = NA ) -} +### Centroids of integer GRaster "clumps" + +# Load elevation raster +madElev <- fastData("madElev") +elev <- fast(madElev) + +# Create clumps of similarly-valued cells +clumps <- clump(elev, minDiff = 0.01, minClumpSize = 1000) + +# Centroids: +clumpCents <- centroids(clumps) +clumpCents + +plot(clumps) +plot(clumpCents, add = TRUE) + } } \seealso{ -\code{\link[terra:centroids]{terra::centroids()}}; \strong{GRASS} addon module \code{v.centerpoint}. +\code{\link[terra:centroids]{terra::centroids()}}; \strong{GRASS} addon tools \code{v.centerpoint} and \code{r.centroids}. } diff --git a/man/clusterPoints.Rd b/man/clusterPoints.Rd index fd1c8599..d645cfcd 100644 --- a/man/clusterPoints.Rd +++ b/man/clusterPoints.Rd @@ -10,7 +10,7 @@ \arguments{ \item{x}{A "points" \code{GVector}.} -\item{method}{Character: Method used to identify clusters. Explanations of methods are provided in the help page for the \strong{GRASS} module \code{v.cluster}, available using \code{grassHelp("v.cluster")}. +\item{method}{Character: Method used to identify clusters. Explanations of methods are provided in the help page for the \strong{GRASS} tool \code{v.cluster}, available using \code{grassHelp("v.cluster")}. \itemize{ \item \code{"DBSCAN"} (default): Density-Based Spatial Clustering of Applications with Noise. \item \code{"DBSCAN2"}: A modification of DBSCAN. @@ -32,5 +32,5 @@ A vector of integers indicating the cluster to which each point belongs. \code{clusterPoints()} partitions points in a "points" \code{GVector} into clusters. } \seealso{ -\strong{GRASS} manual page for module \code{v.cluster} (see \code{grassHelp("v.cluster")}) +\strong{GRASS} manual page for tool \code{v.cluster} (see \code{grassHelp("v.cluster")}) } diff --git a/man/compareGeom.Rd b/man/compareGeom.Rd index 9625185d..40b7a5ca 100644 --- a/man/compareGeom.Rd +++ b/man/compareGeom.Rd @@ -95,7 +95,7 @@ \item{stopOnError}{Logical: If \code{TRUE} (default), throw an error with an explanation if the objects are not comparable. If \code{FALSE} (default), return \code{TRUE} or \code{FALSE}.} -\item{messages}{Logical: If \verb{TRUE (default), display a warning if a condition is not met. This only comes into effect if }stopOnError\code{is}FALSE`.} +\item{messages}{Logical: If \code{TRUE} (default), display a warning if a condition is not met. This only comes into effect if \code{stopOnError} is \code{FALSE}.} \item{geometry}{Logical (vector-vector comparison only): Compare geometry. Default is \code{FALSE}.} } diff --git a/man/compositeRGB.Rd b/man/compositeRGB.Rd index 3babfa56..ced9cb26 100644 --- a/man/compositeRGB.Rd +++ b/man/compositeRGB.Rd @@ -57,5 +57,5 @@ plot(comp, col = grays) } } \seealso{ -\code{\link[=plotRGB]{plotRGB()}}, \code{\link[terra:plotRGB]{terra::plotRGB()}}, \strong{GRASS} manual page for module \code{r.composite} (see \code{grassHelp("r.composite")}) +\code{\link[=plotRGB]{plotRGB()}}, \code{\link[terra:plotRGB]{terra::plotRGB()}}, \strong{GRASS} manual page for tool \code{r.composite} (see \code{grassHelp("r.composite")}) } diff --git a/man/concats.Rd b/man/concats.Rd index 716014b2..dfeaf901 100644 --- a/man/concats.Rd +++ b/man/concats.Rd @@ -152,5 +152,5 @@ levels(combinedNA) } } \seealso{ -\code{\link[=combineLevels]{combineLevels()}}, \code{\link[terra:concats]{terra::concats()}}, \code{vignette("GRasters", package = "fasterRaster")}, \strong{GRASS} manual page for module \code{r.cross} (see \code{grassHelp("r.cross")}) +\code{\link[=combineLevels]{combineLevels()}}, \code{\link[terra:concats]{terra::concats()}}, \code{vignette("GRasters", package = "fasterRaster")}, \strong{GRASS} manual page for tool \code{r.cross} (see \code{grassHelp("r.cross")}) } diff --git a/man/connectors.Rd b/man/connectors.Rd index 3c319b28..5891670e 100644 --- a/man/connectors.Rd +++ b/man/connectors.Rd @@ -49,5 +49,5 @@ plot(consFromRivers, col = "red", add = TRUE) } } \seealso{ -\strong{GRASS} manual for module \code{v.distance} (see \code{grassHelp("v.distance")}). +\strong{GRASS} manual for tool \code{v.distance} (see \code{grassHelp("v.distance")}). } diff --git a/man/convHull.Rd b/man/convHull.Rd index 154c53e7..ae98ffa8 100644 --- a/man/convHull.Rd +++ b/man/convHull.Rd @@ -48,5 +48,5 @@ for (i in 1:n) { } } \seealso{ -\code{link[terra]{convHull}}, \code{link[sf]{st_convex_hull}}, module \code{v.hull} in \strong{GRASS} (see \code{grassHelp("v.hull")}) +\code{link[terra]{convHull}}, \code{link[sf]{st_convex_hull}}, tool \code{v.hull} in \strong{GRASS} (see \code{grassHelp("v.hull")}) } diff --git a/man/delaunay.Rd b/man/delaunay.Rd index 34798fc2..c4a15e4c 100644 --- a/man/delaunay.Rd +++ b/man/delaunay.Rd @@ -48,5 +48,5 @@ plot(rand) } } \seealso{ -\code{\link[terra:voronoi]{terra::delaunay()}}, module \code{v.delaunay} in \strong{GRASS} +\code{\link[terra:voronoi]{terra::delaunay()}}, tool \code{v.delaunay} in \strong{GRASS} } diff --git a/man/denoise.Rd b/man/denoise.Rd index 4fe5d9bb..8a3f77f4 100644 --- a/man/denoise.Rd +++ b/man/denoise.Rd @@ -59,5 +59,5 @@ plot(compare2) } } \seealso{ -\code{\link[=princomp]{princomp()}}, \code{\link[stats:prcomp]{stats::prcomp()}}, \strong{GRASS} manual page for module \code{i.pca} (see \code{grassHelp("i.pca")}) +\code{\link[=princomp]{princomp()}}, \code{\link[stats:prcomp]{stats::prcomp()}}, \strong{GRASS} manual page for tool \code{i.pca} (see \code{grassHelp("i.pca")}) } diff --git a/man/dot-g.proj.Rd b/man/dot-g.proj.Rd index cb84e943..fc72156d 100644 --- a/man/dot-g.proj.Rd +++ b/man/dot-g.proj.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/g.proj.r \name{.g.proj} \alias{.g.proj} -\title{Call GRASS \code{g.proj} module} +\title{Call GRASS \code{g.proj} tool} \usage{ .g.proj() } @@ -10,6 +10,6 @@ Displays current projection information for the active "project/location" in \strong{GRASS}. } \description{ -This function calls the \strong{GRASS} module \code{g.region} to display information on the projection of the current \strong{GRASS} "project". +This function calls the \strong{GRASS} tool \code{g.region} to display information on the projection of the current \strong{GRASS} "project". } \keyword{internal} diff --git a/man/dot-g.region.Rd b/man/dot-g.region.Rd index 4ea84c2b..526fe786 100644 --- a/man/dot-g.region.Rd +++ b/man/dot-g.region.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/g.region.r \name{.g.region} \alias{.g.region} -\title{Call GRASS \code{g.region} module} +\title{Call GRASS \code{g.region} tool} \usage{ .g.region() } @@ -10,6 +10,6 @@ Displays current region information for the active "project/location" in \strong{GRASS}. } \description{ -This function calls the \strong{GRASS} module \code{g.region} to display information on the region of the current \strong{GRASS} "project". +This function calls the \strong{GRASS} tool \code{g.region} to display information on the region of the current \strong{GRASS} "project". } \keyword{internal} diff --git a/man/dot-makeGVector.Rd b/man/dot-makeGVector.Rd index cf02c482..35df7bb4 100644 --- a/man/dot-makeGVector.Rd +++ b/man/dot-makeGVector.Rd @@ -18,7 +18,7 @@ \item{table}{A \code{data.table}, \code{data.frame}, \code{GVector} with a table, or character. This can be \code{data.table(NULL)} or \code{data.frame(NULL)} if there is no table associated with the vector. If a character, this is interpreted as the name of the table in \strong{GRASS}.} -\item{build}{Logical: If \code{TRUE} (default), build topology using \strong{GRASS} module \code{v.build}.} +\item{build}{Logical: If \code{TRUE} (default), build topology using \strong{GRASS} tool \code{v.build}.} \item{extensive}{Logical: If \code{TRUE}, do extensive topological checks using \code{v.build}. The default is \code{FALSE}.} diff --git a/man/dot-makeSourceName.Rd b/man/dot-makeSourceName.Rd index ce4ff454..ac71fac8 100644 --- a/man/dot-makeSourceName.Rd +++ b/man/dot-makeSourceName.Rd @@ -7,7 +7,7 @@ .makeSourceName(x = NULL, type = NULL, n = 1L, name = NULL) } \arguments{ -\item{x}{Character or \code{NULL}: Descriptive string. \strong{Developers, please note}: To assist with debugging, \strong{GRASS} objects created by a \strong{GRASS} module have the module named in this argument (with underscores). Example: "v_in_ogr" or "r_resample".} +\item{x}{Character or \code{NULL}: Descriptive string. \strong{Developers, please note}: To assist with debugging, \strong{GRASS} objects created by a \strong{GRASS} tool have the tool named in this argument (with underscores). Example: "v_in_ogr" or "r_resample".} \item{type}{Character: \code{raster}, \code{raster3D}, \code{vector}, or \code{table}.} diff --git a/man/examples/ex_GRaster_GVector_subset_assign.r b/man/examples/ex_GRaster_GVector_subset_assign.r index 4773fab2..cbba1436 100644 --- a/man/examples/ex_GRaster_GVector_subset_assign.r +++ b/man/examples/ex_GRaster_GVector_subset_assign.r @@ -68,6 +68,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -76,14 +77,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -92,9 +99,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/examples/ex_addons.r b/man/examples/ex_addons.r index d261d32c..9ef1e703 100644 --- a/man/examples/ex_addons.r +++ b/man/examples/ex_addons.r @@ -1,13 +1,9 @@ if (grassStarted()) { -# Does the addons folder exist? -ao <- addons(fail = "warning") -if (ao) print("Addons is folder is probably correctly specified.") +# What addons are installed? +addons() -# Does this particular module exist? -addon <- "v.centerpoint" -exten <- addons(addon, fail = FALSE) - -if (exten) print("Extension `v.centerpoints` is installed.") +# Is a specific addon installed? +addons(c("v.centerpoint", "fake.addon")) } diff --git a/man/examples/ex_centroids.r b/man/examples/ex_centroids.r index 77a283f3..900f1f96 100644 --- a/man/examples/ex_centroids.r +++ b/man/examples/ex_centroids.r @@ -4,74 +4,80 @@ if (grassStarted()) { library(sf) library(terra) -# Points, lines, and polygons -madDypsis <- fastData("madDypsis") -madRivers <- fastData("madRivers") -madCoast4 <- fastData("madCoast4") - -# Convert to GVectors: -dypsis <- fast(madDypsis) -rivers <- fast(madRivers) -coast4 <- fast(madCoast4) +### Points, line, and polygon centroids # Point centroids: -dypMean <- centroids(dypsis, fail = FALSE) -dypMedian <- centroids(dypsis, method = "median", fail = FALSE) -dypPMedian <- centroids(dypsis, method = "pmedian", fail = FALSE) +madDypsis <- fastData("madDypsis") +dypsis <- fast(madDypsis) -if (!is.null(dypMean)) { +dypMean <- centroids(dypsis) +dypMedian <- centroids(dypsis, method = "median") +dypPMedian <- centroids(dypsis, method = "pmedian") plot(dypsis) plot(dypMean, col = "red", add = TRUE) plot(dypMedian, col = "green", pch = 2, add = TRUE) -plot(dypPMedian, col = "orange", pch = 1, add = TRUE) +plot(dypPMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mean", "median", "pmedian"), - col = c("red", "green", "orange"), - pch = c(16, 2, 1), + col = c("red", "green", "blue"), + pch = c(16, 2, 3), xpd = NA ) -} - # Line centroids: -riversMid <- centroids(rivers, fail = FALSE) -riversMean <- centroids(rivers, method = "mean", fail = FALSE) -riversMedian <- centroids(rivers, method = "median", fail = FALSE) +madRivers <- fastData("madRivers") +rivers <- fast(madRivers) -if (!is.null(riversMid)) { +riversMid <- centroids(rivers) +riversMean <- centroids(rivers, method = "mean") +riversMedian <- centroids(rivers, method = "median") plot(rivers) plot(riversMid, col = "red", add = TRUE) plot(riversMean, col = "green", pch = 2, add = TRUE) -plot(riversMedian, col = "orange", pch = 1, add = TRUE) +plot(riversMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mid", "mean", "median"), - col = c("red", "green", "orange"), - pch = c(16, 2, 1), + col = c("red", "green", "blue"), + pch = c(16, 2, 3), xpd = NA ) -} - # Polygon centroids: -coastMean <- centroids(coast4, fail = FALSE) -coastMedian <- centroids(coast4, method = "median", fail = FALSE) -coastBMedian <- centroids(coast4, method = "bmedian", fail = FALSE) +madCoast4 <- fastData("madCoast4") +coast4 <- fast(madCoast4) -if (!is.null(coastMean)) { +coastMean <- centroids(coast4) +coastMedian <- centroids(coast4, method = "median") +coastBMedian <- centroids(coast4, method = "bmedian") plot(coast4) plot(coastMean, col = "red", add = TRUE) plot(coastMedian, col = "green", pch = 2, add = TRUE) -plot(coastBMedian, col = "orange", pch = 1, add = TRUE) +plot(coastBMedian, col = "blue", pch = 3, add = TRUE) legend("bottomright", legend = c("mean", "median", "bmedian"), - col = c("red", "green", "orange"), + col = c("red", "green", "blue"), pch = c(16, 2, 1), xpd = NA ) -} +### Centroids of integer GRaster "clumps" + +# Load elevation raster +madElev <- fastData("madElev") +elev <- fast(madElev) + +# Create clumps of similarly-valued cells +clumps <- clump(elev, minDiff = 0.01, minClumpSize = 1000) + +# Centroids: +clumpCents <- centroids(clumps) +clumpCents + +plot(clumps) +plot(clumpCents, add = TRUE) + } diff --git a/man/examples/ex_multivarEnvSim.r b/man/examples/ex_multivarEnvSim.r new file mode 100644 index 00000000..0053a9ba --- /dev/null +++ b/man/examples/ex_multivarEnvSim.r @@ -0,0 +1,31 @@ +if (grassStarted()) { + +# Setup +library(terra) + +# Climatic conditions with 4 variables +madChelsa <- fastData("madChelsa") +chelsa <- fast(madChelsa) + +# Simulate new conditions by multiplying values by (1 + small number) +proj <- 1.05 * chelsa +names(proj) <- names(chelsa) # proj must have same names as ref + +messes <- multivarEnvSim(ref = chelsa, proj = proj) +plot(messes) + +# Where is at least one variable outside the reference range? +extrap <- messes[["MESS"]] < 0 +levs <- data.frame(value = 0:1, labels = c('no extrapolation', 'extrapolation')) +levels(extrap) <- levs +plot(extrap) + +# Using a data frame as "reference" conditions: +madDypsis <- fastData("madDypsis") # Dypsis occurrences +dypsis <- fast(madDypsis) + +dypEnv <- extract(chelsa, dypsis) +dypMess <- multivarEnvSim(ref = dypEnv, proj = proj) +plot(dypMess) + +} diff --git a/man/examples/ex_neighborhoodMatrix.r b/man/examples/ex_neighborhoodMatrix.r new file mode 100644 index 00000000..5c760cc2 --- /dev/null +++ b/man/examples/ex_neighborhoodMatrix.r @@ -0,0 +1,13 @@ +if (grassStarted()) { + +# Setup +library(sf) + +# Polygons vector: +madCoast4 <- fastData(madCoast4) +mc4 <- fast(madCoast4) + +neighs <- neighborhoodMatrix(mc4) +neighs + +} diff --git a/man/examples/ex_randRast.r b/man/examples/ex_randRast.r index 3df33205..71d0e68a 100644 --- a/man/examples/ex_randRast.r +++ b/man/examples/ex_randRast.r @@ -11,11 +11,11 @@ madElev <- fastData("madElev") elev <- fast(madElev) ### Create a raster with values drawn from a uniform distribution: -unif <- runifRast(elev) +unif <- rUnifRast(elev) plot(unif) ### Create a raster with values drawn from a normal distribution: -norms <- rnormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) plot(norms) hist(norms, bins = 100) @@ -34,4 +34,23 @@ fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) plot(fractal) hist(fractal) +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + } diff --git a/man/examples/ex_ruggedness_wetness.r b/man/examples/ex_ruggedness_wetness.r index ca6ccba9..d6b6a3df 100644 --- a/man/examples/ex_ruggedness_wetness.r +++ b/man/examples/ex_ruggedness_wetness.r @@ -9,12 +9,18 @@ madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) -# Terrain ruggedness index: -tri <- ruggedness(elev) -plot(c(elev, tri)) - # Topographic wetness index: twi <- wetness(elev) +names(twi) <- 'TWI' plot(c(elev, twi)) +# Terrain ruggedness index: +tri <- ruggedness(elev) +tri7 <- ruggedness(elev, size = 7) +triSmooth7 <- ruggedness(elev, size = 7, exponent = 4) + +tris <- c(elev, tri, tri7, triSmooth7) +names(tris) <- c("elevation", "TRI in 3x3", "TRI in 7x7", "Smoothed TRIin 7x7") +plot(tris) + } diff --git a/man/fast.Rd b/man/fast.Rd index 35cb4571..7d512906 100644 --- a/man/fast.Rd +++ b/man/fast.Rd @@ -143,13 +143,13 @@ By default, \code{fast()} will try to correct topological errors in vectors. The Issues can also arise due to: \itemize{ \item \strong{Data table-vector mismatching}: If your vector has a data table ("attribute table") associated with it, errors can occur if there are more/fewer geometries (or multi-geometries) per row in the table. If you do not really need the data table to do your analysis, you can remove it (and thus obviate this error) using \code{dropTable = TRUE}. -\item \strong{Dissolving or aggregating "invalid" geometries}: Using the \code{resolve} argument, you can create a topologically valid vector by either coercing all overlapping portions of polygons into their own geometries (\code{resolve = "disaggregate"}), or by coercing them into a single, combined geometry (\code{resolve = "aggregate"}). Aggregation/disaggregation will be implemented after loading the vector into \strong{GRASS} using the settings given by \code{snap} and \code{area}. Aggregation/disaggregation will cause any associated data table to be dropped (it forces \code{dropTable} to be \code{TRUE}). The default action is to do neither aggregation nor disaggregation (\code{resolve = NA}). +\item \strong{Dissolving or aggregating "invalid" geometries}: Using the \code{resolve} argument, you can create a topologically valid vector by either coercing all overlapping portions of polygons into their own geometries (\code{resolve = "disaggregate"}), or by coercing them into a single, combined geometry (\code{resolve = "aggregate"}). Aggregation/disaggregation will be implemented after loading the vector into \strong{GRASS} using the settings given by \code{snap} and \code{area}. Aggregation/disaggregation will cause any associated data table to be dropped (it forces \code{dropTable} to be \code{TRUE}). The default action is to do neither aggregation nor disaggregation (\code{resolve = NA}). You can also do this outside \strong{fasterRaster} using \code{\link[terra:aggregate]{terra::aggregate()}} or \code{\link[terra:disaggregate]{terra::disagg()}}. } If none of these fixes work, you can try: \itemize{ -\item \strong{Correction outside of \emph{fasterRaster}}: Before you convert the vector into \strong{fasterRaster}'s \code{GVector} format, you can also try using the \code{\link[terra:is.valid]{terra::makeValid()}} or \code{\link[sf:valid]{sf::st_make_valid()}} tools to fix issues, then use \code{fast()}. -\item \strong{Post-conversion to a \code{GVector}}: If you do get a vector loaded into \code{GVector} format, you can also use a set of \strong{fasterRaster} vector-manipulation \link[=breakPolys]{tools} or \code{\link[=fillHoles]{fillHoles()}} to fix issues. +\item \strong{Correction outside of \emph{fasterRaster}}: Before you convert the vector into \strong{fasterRaster}'s \code{GVector} format, you can also try using the \code{\link[terra:is.valid]{terra::makeValid()}} or \code{\link[sf:valid]{sf::st_make_valid()}} tools to fix issues, then use \code{fast()}. You can also use \code{\link[terra:aggregate]{terra::aggregate()}} or \code{\link[terra:disaggregate]{terra::disagg()}} to combine/split problematic geometries. +\item \strong{Post-load correction}: If you do get a vector loaded into \code{GVector} format, you can also use a set of \strong{fasterRaster} vector-manipulation \link[=breakPolys]{tools} or \code{\link[=fillHoles]{fillHoles()}} to fix issues. } } \examples{ diff --git a/man/fasterRaster.Rd b/man/fasterRaster.Rd index c0e85a21..13bee210 100644 --- a/man/fasterRaster.Rd +++ b/man/fasterRaster.Rd @@ -4,20 +4,18 @@ \name{fasterRaster} \alias{fasterRaster-package} \alias{fasterRaster} -\title{"fasterRaster": Faster raster and spatial vector processing using "GRASS GIS"} +\title{"fasterRaster": Faster raster and spatial vector processing using "GRASS"} \description{ -\strong{fasterRaster}: Processing of large-in-memory/-on disk rasters and spatial vectors in using \strong{GRASS GIS}. Most functions in the \strong{terra} and \strong{sf} packages are recreated. Processing of medium-sized and smaller spatial objects will nearly always be faster using \strong{terra} or \strong{sf}. To use most of the functions you must have the stand-alone version of \strong{GRASS GIS} version 8.3 or higher (not the \strong{OSGeoW4} installer version). Note that due to differences in how \strong{GRASS}, \strong{terra}, and \strong{sf} were implemented, results will not always be strictly comparable between functions for the same operation. +\strong{fasterRaster}: Processing of large-in-memory/-on disk rasters and spatial vectors in using \strong{GRASS}. Most functions in the \strong{terra} and \strong{sf} packages are recreated. Processing of medium-sized and smaller spatial objects will nearly always be faster using \strong{terra} or \strong{sf}. To use most of the functions you must have the stand-alone version of \strong{GRASS} version 8.3 or higher (not the \strong{OSGeoW4} installer version). Note that due to differences in how \strong{GRASS}, \strong{terra}, and \strong{sf} were implemented, results will not always be strictly comparable between functions for the same operation. \subsection{Most useful tutorials and functions:}{ \itemize{ \item The quick-start guide to getting started with \strong{fasterRaster}: \code{vignette("fasterRaster", package = "fasterRaster")}: \item Types of \code{GRaster}s: \code{vignette("GRasters", package = "fasterRaster")} \item How to speed up \strong{fasterRaster}: \code{vignette("faster_fasterRaster", package = "fasterRaster")} -\item Using functions that depend on \strong{GRASS} addons: \code{vignette("addons", package = "fasterRaster")} \item \code{\link[=faster]{faster()}}: Set the directory where \strong{GRASS} is installed on your system, and set or get other package-wide options. This function must be run once before using most \strong{fasterRaster} functions. \item \code{\link[=fast]{fast()}}: Convert a \code{SpatRaster}, \code{SpatVector}, or \code{sf} vector to \strong{fasterRaster}'s raster format (\code{GRaster}s) or vector format (\code{GVector}s), or load one from a file \item \code{\link[=rast]{rast()}}, \code{\link[=vect]{vect()}}, and \code{\link[=st_as_sf]{st_as_sf()}}: Convert \code{GRaster}s and \code{GVector}s to \code{SpatRaster}s, \code{SpatVector}s, or \code{sf} vectors \item \code{\link[=writeRaster]{writeRaster()}} and \code{\link[=writeVector]{writeVector()}}: Save \code{GRaster}s or \code{GVector}s to disk -\item \code{\link[=addons]{addons()}}: Test if the \code{addons} directory is correct and if a particular addon \strong{GRASS} module is installed. } } @@ -119,6 +117,7 @@ Operations on \code{GRaster}s \item \code{\link[=maskNA]{maskNA()}}: Mask all non-NA cells or all NA cells \item \code{\link[=match]{match()}}, \code{\link[fasterRaster]{\%in\%}}, and \code{\link[fasterRaster]{\%notin\%}}: Find which cells of a \code{GRaster} match or do not match certain values \item \code{\link[=merge]{merge()}}: Combine two or more rasters with different extents and fill in \code{NA}s +\item \code{\link[=multivarEnvSim]{multivarEnvSim()}}: Multivariate environmental similarity surface (MESS) \item \code{\link[fasterRaster]{names<-}}: Assign names to a \code{GRaster} \item \code{\link[=noise]{noise()}}: Remove coarse-scale trends from a \code{GRaster}, leaving just fine-scale "noise" \item \code{\link[=pairs]{pairs()}}: Plot correlations between \code{GRaster} layers @@ -149,9 +148,10 @@ Operations on \code{GRaster}s \item \code{\link[=fractalRast]{fractalRast()}}: Create a fractal \code{GRaster} \item \code{\link[=init]{init()}}: GRaster with values equal to row, column, coordinate, regular, or "chess" \item \code{\link[=longlat]{longlat()}}: Create longitude/latitude rasters -\item \code{\link[=rnormRast]{rnormRast()}}: A random \code{GRaster} with values drawn from a normal distribution +\item \code{\link[=rNormRast]{rNormRast()}}: A random \code{GRaster} with values drawn from a normal distribution \item \code{\link[=rSpatialDepRast]{rSpatialDepRast()}}: Create a random \code{GRaster} with or without spatial dependence -\item \code{\link[=runifRast]{runifRast()}}: A random \code{GRaster} with values drawn from a uniform distribution +\item \code{\link[=rUnifRast]{rUnifRast()}}: A random \code{GRaster} with values drawn from a uniform distribution +\item \code{\link[=rWalkRast]{rWalkRast()}}: Paths of random walkers \item \code{\link[=sineRast]{sineRast()}}: Sine wave rasters } } @@ -279,6 +279,7 @@ Operations on \code{GRaster}s \item \code{\link[=kernel]{kernel()}}: Kernel density estimator of points \item \code{\link[=missing.cases]{missing.cases()}}: Find rows of a \code{GVector}'s data table that have at least \code{NA} in them \item \code{\link[fasterRaster]{names<-}}: Assign names to columns of a \code{GVector}s data table +\item \code{\link[=neighborhoodMatrix]{neighborhoodMatrix()}} and \code{\link[=neighbourhoodMatrix]{neighbourhoodMatrix()}}: Neighborhood matrix of a polygons \code{GVector} \item \code{\link[=project]{project()}}: Change coordinate reference system \item \code{\link[=rasterize]{rasterize()}}: Convert a \code{GVector} to a \code{GRaster} \item \code{\link[=rbind]{rbind()}}: Combine \code{GVectors} @@ -340,15 +341,18 @@ Operations on \code{GRaster}s \subsection{General purpose functions}{ \itemize{ +\item \code{\link[=addons]{addons()}}: Show installed \strong{GRASS} addons \item \code{\link[=compareGeom]{compareGeom()}}: Determine if geographic metadata is same between \code{GRaster}s and/or \code{GVector}s \item \code{\link[=dropRows]{dropRows()}}: Remove rows from a \code{data.frame} or \code{data.table} \item \code{\link[=grassGUI]{grassGUI()}}: Start the \strong{GRASS} GUI (not recommended for most users!!!) -\item \code{\link[=grassHelp]{grassHelp()}}: Open the help page for a \strong{GRASS} module. +\item \code{\link[=grassHelp]{grassHelp()}}: Open the help page for a \strong{GRASS} tool. \item \code{\link[=grassInfo]{grassInfo()}}: \strong{GRASS} version and citation \item \code{\link[=grassStarted]{grassStarted()}}: Has a connection \strong{GRASS} been made within the current \strong{R} session? +\item \code{\link[=installAddon]{installAddon()}}: Install a \strong{GRASS} addon \item \code{\link[=mow]{mow()}}: Remove unused rasters and vectors from the \strong{GRASS} cache \item \code{\link[=reorient]{reorient()}}: Convert degrees between 'north-orientation' and 'east orientation' \item \code{\link[=replaceNAs]{replaceNAs()}}: Replace \code{NA}s in columns of a \code{data.table} or \code{data.frame}, or in a vector +\item \code{\link[=removeAddon]{removeAddon()}}: Delete \strong{GRASS} addon from your system \item \code{\link[=seqToSQL]{seqToSQL()}}: Format a numeric series into an SQL value call \item \code{\link[=update]{update()}}: Refresh metadata in a \code{GRaster} or \code{GVector} object } diff --git a/man/figures/logo.png b/man/figures/logo.png index 2f40d427..b9e42114 100644 Binary files a/man/figures/logo.png and b/man/figures/logo.png differ diff --git a/man/fillHoles.Rd b/man/fillHoles.Rd index b4b097af..2fbd5455 100644 --- a/man/fillHoles.Rd +++ b/man/fillHoles.Rd @@ -127,5 +127,5 @@ filled <- fillHoles(holes, fail = FALSE) } } \seealso{ -\code{\link[terra:fill]{terra::fillHoles()}}, \strong{GRASS} manual page for module \code{v.fill.holes} (see \code{grassHelp("v.fill.holes")}) +\code{\link[terra:fill]{terra::fillHoles()}}, \strong{GRASS} manual page for tool \code{v.fill.holes} (see \code{grassHelp("v.fill.holes")}) } diff --git a/man/fillNAs.Rd b/man/fillNAs.Rd index b2ddb748..e5346d85 100644 --- a/man/fillNAs.Rd +++ b/man/fillNAs.Rd @@ -71,5 +71,5 @@ plot(maps) } } \seealso{ -\code{\link[terra:interpNear]{terra::interpNear()}}, \strong{GRASS} module \code{r.fillnulls} (see \code{grassHelp("r.fillnulls")}) +\code{\link[terra:interpNear]{terra::interpNear()}}, \strong{GRASS} tool \code{r.fillnulls} (see \code{grassHelp("r.fillnulls")}) } diff --git a/man/flow.Rd b/man/flow.Rd index 1ed5194b..d8acec51 100644 --- a/man/flow.Rd +++ b/man/flow.Rd @@ -30,7 +30,7 @@ \item{dirThreshold}{Numeric (default is \code{Inf}): For the multi-direction flow model, this indicates the amount of accumulated flow above which the single-direction flow rule is used to locate the egress of water from a cell. This is the \code{d8cut} parameter in \code{r.stream.extract}.} -\item{scratchDir}{Character or \code{NULL} (default): Directory in which to store temporary files. The \strong{GRASS} module \code{r.terraflow} makes a lot of temporary files. If this is \code{NULL}, then a temporary folder in the user's working directory will be used (see \code{\link[=getwd]{getwd()}}).} +\item{scratchDir}{Character or \code{NULL} (default): Directory in which to store temporary files. The \strong{GRASS} tool \code{r.terraflow} makes a lot of temporary files. If this is \code{NULL}, then a temporary folder in the user's working directory will be used (see \code{\link[=getwd]{getwd()}}).} } \value{ A \code{GRaster}. @@ -45,7 +45,7 @@ The \code{flow()} function uses a raster representing elevation to compute other \item Topographic convergence (log of flow accumulation divided by local slope). } -More details about the computations can be found at the help page for the \strong{GRASS} module \code{r.terraflow}] (see \code{grassHelp("r.terraflow")}) +More details about the computations can be found at the help page for the \strong{GRASS} tool \code{r.terraflow}] (see \code{grassHelp("r.terraflow")}) } \examples{ if (grassStarted()) { @@ -67,5 +67,5 @@ plot(elevWater) } } \seealso{ -\code{\link[=flowPath]{flowPath()}}, \code{\link[=streams]{streams()}}, the \strong{GRASS} module \code{r.terraflow} (see \code{grassHelp("r.terraflow")}) +\code{\link[=flowPath]{flowPath()}}, \code{\link[=streams]{streams()}}, the \strong{GRASS} tool \code{r.terraflow} (see \code{grassHelp("r.terraflow")}) } diff --git a/man/flowPath.Rd b/man/flowPath.Rd index 3f7838a8..61736696 100644 --- a/man/flowPath.Rd +++ b/man/flowPath.Rd @@ -72,5 +72,5 @@ seqLines } } \seealso{ -\code{\link[=flow]{flow()}}, \code{\link[=streams]{streams()}}, the \strong{GRASS} module \code{r.drain} (see \code{grassHelp("r.drain")}) +\code{\link[=flow]{flow()}}, \code{\link[=streams]{streams()}}, the \strong{GRASS} tool \code{r.drain} (see \code{grassHelp("r.drain")}) } diff --git a/man/focal.Rd b/man/focal.Rd index ea0284b2..e2243308 100644 --- a/man/focal.Rd +++ b/man/focal.Rd @@ -25,13 +25,13 @@ \item "\code{min}" or "\code{max}": Minimum or maximum. Should not use a weights matrix. \item "\code{range}": Difference between the maximum and minimum. Should not use a weights matrix. \item "\code{sd}": Sample standard deviation. NB: This is the same as the \code{\link[stats:sd]{stats::sd()}} function. -\item "\code{sdpop}": Population standard deviation. NB: This is the same as the function "stddev" in the \strong{GRASS} module \code{r.neighbors}. +\item "\code{sdpop}": Population standard deviation. NB: This is the same as the function "stddev" in the \strong{GRASS} tool \code{r.neighbors}. \item "\code{sum}": Sum of non-`NA`` cells. \item "\code{count}": Number of non-`NA cells. Should not use a weights matrix. \item "\code{var}": Sample variance. NB: This is the same as the \code{\link[stats:cor]{stats::var()}} function. -\item "\code{varpop}": Population variance. NB: This is the same as the function "variance" in the \strong{GRASS} module \code{r.neighbors}. +\item "\code{varpop}": Population variance. NB: This is the same as the function "variance" in the \strong{GRASS} tool \code{r.neighbors}. \item "\code{nunique}": Number of unique values. Should not use a weights matrix. -\item "\code{interspersion}": Proportion of cells with values different from focal cell (e.g., if 6 of 8 cells have different values, then the interspersion is 6/8 = 0.75). NB: This is slightly different from how it is defined in the \strong{GRASS} module \code{r.neighbors}. Should not use a weights matrix. +\item "\code{interspersion}": Proportion of cells with values different from focal cell (e.g., if 6 of 8 cells have different values, then the interspersion is 6/8 = 0.75). NB: This is slightly different from how it is defined in the \strong{GRASS} tool \code{r.neighbors}. Should not use a weights matrix. \item "\code{quantile}": Quantile of values. The value in argument \code{quantile} is used to specify the quantile. } @@ -83,5 +83,5 @@ minmax(s) } } \seealso{ -\code{\link[terra:focal]{terra::focal()}}, \strong{GRASS} manual page for module \code{r.neighbors} (see \code{grassHelp("r.neighbors")}) +\code{\link[terra:focal]{terra::focal()}}, \strong{GRASS} manual page for tool \code{r.neighbors} (see \code{grassHelp("r.neighbors")}) } diff --git a/man/fractalRast.Rd b/man/fractalRast.Rd index 95d3316c..03918d7b 100644 --- a/man/fractalRast.Rd +++ b/man/fractalRast.Rd @@ -36,11 +36,11 @@ madElev <- fastData("madElev") elev <- fast(madElev) ### Create a raster with values drawn from a uniform distribution: -unif <- runifRast(elev) +unif <- rUnifRast(elev) plot(unif) ### Create a raster with values drawn from a normal distribution: -norms <- rnormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) plot(norms) hist(norms, bins = 100) @@ -59,8 +59,27 @@ fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) plot(fractal) hist(fractal) +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + } } \seealso{ -\code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=rnormRast]{rnormRast()}}, \code{\link[=runifRast]{runifRast()}}, \strong{GRASS} manual page for module \code{r.surf.fractal} (see \code{grassHelp("r.surf.fractal")}) +\code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=rNormRast]{rNormRast()}}, \code{\link[=rUnifRast]{rUnifRast()}}, \code{\link[=rWalkRast]{rWalkRast()}}, \strong{GRASS} manual page for tool \code{r.surf.fractal} (see \code{grassHelp("r.surf.fractal")}) } diff --git a/man/fragmentation.Rd b/man/fragmentation.Rd index 38572108..ebc26a02 100644 --- a/man/fragmentation.Rd +++ b/man/fragmentation.Rd @@ -39,7 +39,7 @@ A categorical \code{SpatRaster} or \code{GRaster}. The values assigned to each c \description{ Riitters et al. (2020) propose a classification scheme for forest fragmentation (which can be applied to any habitat type). The scheme relies on calculating density (e.g., number of forested cells in a window around a focal cell) and connectivity (number of cases where neighboring cells are both forested). This function calculates these classes from a \code{GRaster} or \code{SpatRaster} in which the focal habitat type has cell values of 1, and non-focal habitat type has cell values of 0 or \code{NA}. -Note that by default, the \code{SpatRaster} and \code{GRaster} versions will create different results around the border of the raster. The \code{SpatRaster} version uses the \code{\link[terra:focal]{terra::focal()}} function, which will not return an \code{NA} value when its window overlaps the raster border if the \code{na.rm} argument is \code{TRUE}. However, the \code{GRaster} version uses the \strong{GRASS} module \code{r.neighbors}, which does return \code{NA} values in these cases. +Note that by default, the \code{SpatRaster} and \code{GRaster} versions will create different results around the border of the raster. The \code{SpatRaster} version uses the \code{\link[terra:focal]{terra::focal()}} function, which will not return an \code{NA} value when its window overlaps the raster border if the \code{na.rm} argument is \code{TRUE}. However, the \code{GRaster} version uses the \strong{GRASS} tool \code{r.neighbors}, which does return \code{NA} values in these cases. The fragmentation classes are: \itemize{ diff --git a/man/freq.Rd b/man/freq.Rd index 06e12cbd..8f51e09f 100644 --- a/man/freq.Rd +++ b/man/freq.Rd @@ -55,5 +55,5 @@ print(f) } } \seealso{ -\code{\link[terra:freq]{terra::freq()}}, module \code{r.stats} in \strong{GRASS} +\code{\link[terra:freq]{terra::freq()}}, tool \code{r.stats} in \strong{GRASS} } diff --git a/man/geomorphons.Rd b/man/geomorphons.Rd index 7dc8c6eb..6f790288 100644 --- a/man/geomorphons.Rd +++ b/man/geomorphons.Rd @@ -28,7 +28,7 @@ \item{mode}{Character: Method for implementing the zenith/line-of-site search. Partial matching is used: \itemize{ -\item \code{"1"} (default): The "original" geomorphon mode (in \strong{GRASS} module \code{r.geomorphon}, the "anglev1" method) +\item \code{"1"} (default): The "original" geomorphon mode (in \strong{GRASS} tool \code{r.geomorphon}, the "anglev1" method) \item \code{"2"}: Better handling of cases with equal zenith/nadir angles (the "anglev2" method) \item \code{"2d"}: As \code{"2"}, but takes into account zenith/nadir distance ("anglev2_distance" method) }} @@ -37,7 +37,7 @@ A categorical \code{GRaster} where each geomorphon is a category (see \code{vignette("GRasters", package = "fasterRaster")}). } \description{ -Geomorphons are idealized terrain types calculated from an elevator raster based on a moving window of a given size. The window is a torus (which can have an inner radius of 0, so can also be a circle), which allows it to identify geomorphons of a given size while ignoring ones larger or smaller. There are 10 basic geomorphons. Consult the the manual for \strong{GRASS} module \code{r.geomorphon} using \code{grassHelp("r.geomorphon")} for more details and diagrams of each type of geomorphon. Geomorphon types include: +Geomorphons are idealized terrain types calculated from an elevator raster based on a moving window of a given size. The window is a torus (which can have an inner radius of 0, so can also be a circle), which allows it to identify geomorphons of a given size while ignoring ones larger or smaller. There are 10 basic geomorphons. Consult the the manual for \strong{GRASS} tool \code{r.geomorphon} using \code{grassHelp("r.geomorphon")} for more details and diagrams of each type of geomorphon. Geomorphon types include: \enumerate{ \item Flat areas: Focal area has approximately the same elevation as surrounding areas \item Pits: An area is lower than all other surrounding areas @@ -76,5 +76,5 @@ plot(geos, col = col) } } \seealso{ -\strong{GRASS} manual for module \code{r.geomorphon} (see \code{grassHelp("r.geomorphon")}) +\strong{GRASS} manual for tool \code{r.geomorphon} (see \code{grassHelp("r.geomorphon")}) } diff --git a/man/global.Rd b/man/global.Rd index b61c4f5b..ee567d6c 100644 --- a/man/global.Rd +++ b/man/global.Rd @@ -65,5 +65,5 @@ global(elev, "*") # calculate all available functions } } \seealso{ -\code{\link[terra:global]{terra::global()}} and \strong{GRASS} module \code{r.univar} +\code{\link[terra:global]{terra::global()}} and \strong{GRASS} tool \code{r.univar} } diff --git a/man/grassHelp.Rd b/man/grassHelp.Rd index 75dfe366..db9478c5 100644 --- a/man/grassHelp.Rd +++ b/man/grassHelp.Rd @@ -2,14 +2,14 @@ % Please edit documentation in R/grassHelp.r \name{grassHelp} \alias{grassHelp} -\title{Open the help page for a GRASS module} +\title{Open the help page for a GRASS tool} \usage{ grassHelp(x, online = FALSE) } \arguments{ \item{x}{Character: Any of: \itemize{ -\item The name of a \strong{GRASS} module (e.g., \code{"r.mapcalc"}). +\item The name of a \strong{GRASS} tool (e.g., \code{"r.mapcalc"}). \item \code{"toc"}: \strong{GRASS} manual table of contents. \item \code{"index"}: Display an index of topics. }} @@ -20,7 +20,7 @@ grassHelp(x, online = FALSE) Nothing (opens a web page). } \description{ -This function opens the manual page for a \strong{GRASS} module (function) in your browser. +This function opens the manual page for a \strong{GRASS} tool (function) in your browser. } \examples{ if (grassStarted() & interactive()) { diff --git a/man/grid.Rd b/man/grid.Rd index bdd89b51..1a66a328 100644 --- a/man/grid.Rd +++ b/man/grid.Rd @@ -71,5 +71,5 @@ plot(coast, lwd = 2, add = TRUE) } } \seealso{ -\code{\link[=hexagons]{hexagons()}}, module \code{v.mkgrid} in \strong{GRASS} +\code{\link[=hexagons]{hexagons()}}, tool \code{v.mkgrid} in \strong{GRASS} } diff --git a/man/hexagons.Rd b/man/hexagons.Rd index 6a192065..d5a4ee12 100644 --- a/man/hexagons.Rd +++ b/man/hexagons.Rd @@ -67,5 +67,5 @@ plot(coast, lwd = 2, add = TRUE) } } \seealso{ -\code{\link[=grid]{grid()}}, module \code{v.mkgrid} in \strong{GRASS} +\code{\link[=grid]{grid()}}, tool \code{v.mkgrid} in \strong{GRASS} } diff --git a/man/hillshade.Rd b/man/hillshade.Rd index ade4ad40..cbbba2b1 100644 --- a/man/hillshade.Rd +++ b/man/hillshade.Rd @@ -12,7 +12,7 @@ \item{angle}{Numeric: The altitude of the sun above the horizon in degrees. Valid values are in the range [0, 90], and the default value is 45 (half way from the horizon to overhead).} -\item{direction}{The direction (azimuth) in which the sun is shining in degrees. Valid values are in the range 0 to 360. The default is 0, meaning the sun is at due south (180 degrees) and shining due north (0 degrees). Note that in this function, 0 corresponds to north and 180 to south, but in the \strong{GRASS} module \code{r.relief}, "east orientation" is used (0 is east, 90 is north, etc.).} +\item{direction}{The direction (azimuth) in which the sun is shining in degrees. Valid values are in the range 0 to 360. The default is 0, meaning the sun is at due south (180 degrees) and shining due north (0 degrees). Note that in this function, 0 corresponds to north and 180 to south, but in the \strong{GRASS} tool \code{r.relief}, "east orientation" is used (0 is east, 90 is north, etc.).} \item{zscale}{Numeric: Value by which to exaggerate terrain. The default is 1. Numbers greater than this will increase apparent relief, and less than this (even negative) will diminish it.} } diff --git a/man/horizonHeight.Rd b/man/horizonHeight.Rd index b3bfc516..aa301f24 100644 --- a/man/horizonHeight.Rd +++ b/man/horizonHeight.Rd @@ -22,7 +22,7 @@ \item{step}{Numeric integer between 0 and 360, inclusive: Angle step size (in degrees) for calculating horizon height. The direction in which horizon height is calculated is incremented from 0 to 360, with the last value excluded.} -\item{northIs0}{Logical: If \code{TRUE} (default), horizon height calculated in the 0-degree direction will be facing north, and proceed clockwise So, under "north orientation", 0 is north, 90 east, 180 south, and 270 west. If \code{FALSE}, angles are in "east orientation", and proceed counterclockwise from east. So, east is 0, north 90, west 180, and south 270. North orientation is the default for this function in \strong{R}, but east orientation is the default in the \strong{GRASS} module \code{r.horizon}. \strong{Note:} The \code{\link[=sun]{sun()}} function requires aspect to be in east orientation.} +\item{northIs0}{Logical: If \code{TRUE} (default), horizon height calculated in the 0-degree direction will be facing north, and proceed clockwise So, under "north orientation", 0 is north, 90 east, 180 south, and 270 west. If \code{FALSE}, angles are in "east orientation", and proceed counterclockwise from east. So, east is 0, north 90, west 180, and south 270. North orientation is the default for this function in \strong{R}, but east orientation is the default in the \strong{GRASS} tool \code{r.horizon}. \strong{Note:} The \code{\link[=sun]{sun()}} function requires aspect to be in east orientation.} \item{bufferZone}{Numeric >= 0 (default is 0): A buffer of the specified width will be generated around the raster before calculation of horizon angle. If the coordinate system is in longitude/latitude (e.g., WGS84 or NAD83), then this is specified in degrees. Otherwise units are map units (usually meters).} @@ -61,5 +61,5 @@ plot(hhEast) } } \seealso{ -\strong{GRASS} manual page for module \code{r.horizon} (see \code{grassHelp("r.horizon")}) +\strong{GRASS} manual page for tool \code{r.horizon} (see \code{grassHelp("r.horizon")}) } diff --git a/man/interpIDW.Rd b/man/interpIDW.Rd index 7415fc1b..86069a5d 100644 --- a/man/interpIDW.Rd +++ b/man/interpIDW.Rd @@ -25,5 +25,5 @@ A \code{GRaster}. This function interpolates values from a set of points to a raster using inverse distance weighting (IDW). } \seealso{ -\code{\link[terra:interpIDW]{terra::interpIDW()}}, \code{\link[=interpSplines]{interpSplines()}}, \code{\link[=fillNAs]{fillNAs()}}, \strong{GRASS} module \code{v.surf.idw} (se \code{grassHelp("v.surf.idw")}) +\code{\link[terra:interpIDW]{terra::interpIDW()}}, \code{\link[=interpSplines]{interpSplines()}}, \code{\link[=fillNAs]{fillNAs()}}, \strong{GRASS} tool \code{v.surf.idw} (se \code{grassHelp("v.surf.idw")}) } diff --git a/man/interpSplines.Rd b/man/interpSplines.Rd index c0214592..485b7565 100644 --- a/man/interpSplines.Rd +++ b/man/interpSplines.Rd @@ -54,5 +54,5 @@ If you receive the error, "No data within this subregion. Consider increasing sp If cross-validation takes too long, or other warnings/errors persist, you can randomly subsample \code{x} to ~100 points to get an optimum value of \code{lambda} (using \code{interpolate = FALSE}), then use this value in the same function again without cross-validation (setting \code{lambda} equal to this value and \code{interpolate = TRUE}). } \seealso{ -\code{\link[=interpIDW]{interpIDW()}}, \code{\link[=fillNAs]{fillNAs()}}, \strong{GRASS} module \code{v.surf.bspline} (see \code{grassHelp("v.surf.bspline")}) +\code{\link[=interpIDW]{interpIDW()}}, \code{\link[=fillNAs]{fillNAs()}}, \strong{GRASS} tool \code{v.surf.bspline} (see \code{grassHelp("v.surf.bspline")}) } diff --git a/man/kernel.Rd b/man/kernel.Rd index 764592d2..eb1c46d9 100644 --- a/man/kernel.Rd +++ b/man/kernel.Rd @@ -66,5 +66,5 @@ plot(dypsis, add = TRUE, pch = 1) } } \seealso{ -\strong{GRASS} manual page for module \code{v.kernel} (see \code{grassHelp("v.kernel")}) +\strong{GRASS} manual page for tool \code{v.kernel} (see \code{grassHelp("v.kernel")}) } diff --git a/man/mask.Rd b/man/mask.Rd index e683fdac..cd159acc 100644 --- a/man/mask.Rd +++ b/man/mask.Rd @@ -82,5 +82,5 @@ plot(c(elev, byRastAll)) } } \seealso{ -\code{\link[terra:mask]{terra::mask()}}, \strong{GRASS} module \code{r.mask} +\code{\link[terra:mask]{terra::mask()}}, \strong{GRASS} tool \code{r.mask} } diff --git a/man/merge.Rd b/man/merge.Rd index 24fc6e50..67a7a631 100644 --- a/man/merge.Rd +++ b/man/merge.Rd @@ -50,5 +50,5 @@ plot(antMan, main = "Antman!") } } \seealso{ -\code{\link[terra:merge]{terra::merge()}}, \code{\link[terra:mosaic]{terra::mosaic()}}, and \strong{GRASS} module \code{r.patch} +\code{\link[terra:merge]{terra::merge()}}, \code{\link[terra:mosaic]{terra::mosaic()}}, and \strong{GRASS} tool \code{r.patch} } diff --git a/man/multivarEnvSim.Rd b/man/multivarEnvSim.Rd new file mode 100644 index 00000000..d522c209 --- /dev/null +++ b/man/multivarEnvSim.Rd @@ -0,0 +1,74 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/multivarEnvSim.r +\name{multivarEnvSim,GRaster,GRaster-method} +\alias{multivarEnvSim,GRaster,GRaster-method} +\alias{multivarEnvSim} +\alias{multivarEnvSim,GRaster,missing-method} +\alias{multivarEnvSim,data.frame,GRaster-method} +\alias{multivarEnvSim,data.table,GRaster-method} +\alias{multivarEnvSim,matrix,GRaster-method} +\title{Multivariate environmental similarity surface (MESS)} +\usage{ +\S4method{multivarEnvSim}{GRaster,GRaster}(ref, proj) + +\S4method{multivarEnvSim}{GRaster,missing}(ref, proj) + +\S4method{multivarEnvSim}{data.frame,GRaster}(ref, proj, na.rm = FALSE) + +\S4method{multivarEnvSim}{data.table,GRaster}(ref, proj, na.rm = FALSE) + +\S4method{multivarEnvSim}{matrix,GRaster}(ref, proj, na.rm = FALSE) +} +\arguments{ +\item{ref}{A \code{data.frame}, \code{data.table}, a points \code{GVector}, or "stack" of \code{GRasters}: This represents the set of "reference" environmental conditions: +\itemize{ +\item \code{data.frame} or \code{data.table}: There must be one column per layer in \code{proj}, and the columns must have the same names as the layers in \code{proj}. +\item \code{GRaster} with one or more layers: Must have the same \code{\link[=names]{names()}} as the \code{GRaster}s in \code{proj}. Values are assumed to be continuous (not categorical/factors). +}} + +\item{proj}{A \code{GRaster} or missing. If a \code{GRaster}, it must have the same layers as can have with one or more layers as \code{ref}. Values are assumed to be continuous (not categorical/factors). If missing, then \code{ref} is used, in which case the output represents the relative difference of each cell from the overall layer median.} + +\item{na.rm}{Logical: If \code{FALSE} (default), and \code{ref} is a \code{data.frame}, \code{data.table}, or \code{matrix}, and has \code{NA}s in it, then the function will likely fail.} +} +\value{ +A \code{GRaster} "stack". There will be one layer per layer in \code{ref}, indicating the MESS score for that variable. There will also be a layer named "MESS" which represents the MESS value across all variables (the minimum value of each of the individual MESS rasters). A final layer represents the layer which is most different (has the lowest MESS value). +} +\description{ +The multivariate environmental similarity surface (MESS) indicates the degree to which a set of "projection" environmental conditions fall inside or outside a set of "reference" conditions. Values of 1 indicate a location falls at the exact median of all variables. Values of 0 indicate that the location has at least one environmental covariate that is at the upper or lower end of the range of reference conditions, and values <1 indicate that at least one variable falls above or below the reference conditions. MESS can be used, for example, to indicate the degree to which a model constructed in one time period and/or location must extrapolate when projected to another time period and/or location. +} +\examples{ +if (grassStarted()) { + +# Setup +library(terra) + +# Climatic conditions with 4 variables +madChelsa <- fastData("madChelsa") +chelsa <- fast(madChelsa) + +# Simulate new conditions by multiplying values by (1 + small number) +proj <- 1.05 * chelsa +names(proj) <- names(chelsa) # proj must have same names as ref + +messes <- multivarEnvSim(ref = chelsa, proj = proj) +plot(messes) + +# Where is at least one variable outside the reference range? +extrap <- messes[["MESS"]] < 0 +levs <- data.frame(value = 0:1, labels = c('no extrapolation', 'extrapolation')) +levels(extrap) <- levs +plot(extrap) + +# Using a data frame as "reference" conditions: +madDypsis <- fastData("madDypsis") # Dypsis occurrences +dypsis <- fast(madDypsis) + +dypEnv <- extract(chelsa, dypsis) +dypMess <- multivarEnvSim(ref = dypEnv, proj = proj) +plot(dypMess) + +} +} +\references{ +Elith, J, Kearney, M, and Phillips, S. 2010. The art of modelling range-shifting species. \emph{Methods in Ecology and Evolution} 1:330-342. \doi{10.1111/j.2041-210X.2010.00036.x} (see especially the Supplement) +} diff --git a/man/neighborhoodMatrix.Rd b/man/neighborhoodMatrix.Rd new file mode 100644 index 00000000..0cf563d4 --- /dev/null +++ b/man/neighborhoodMatrix.Rd @@ -0,0 +1,41 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/neighborhoodMatrix.r +\name{neighborhoodMatrix,GVector-method} +\alias{neighborhoodMatrix,GVector-method} +\alias{neighborhoodMatrix} +\alias{neighbourhoodMatrix,GVector-method} +\alias{neighbourhoodMatrix} +\title{Neighborhood matrix from a polygons GVector} +\usage{ +\S4method{neighborhoodMatrix}{GVector}(x) + +\S4method{neighbourhoodMatrix}{GVector}(x) +} +\arguments{ +\item{x}{A polygons `GVector.} +} +\value{ +A \code{list}. Each element represents a polygon. If an element is empty, it has no neighbors. Otherwise, it is a vector of integers, which represent the indices of the polygon(s) to which it is a neighbor. +} +\description{ +This function returns a neighborhood matrix from a polygons \code{GVector}, which represents which geometries touch one another. It is useful for implementing geostatistical analyses that require indicators about which area features are next to one another. + +Polygons must share more than one point for them to be considered a neighbors (i.e., same as \code{spdep::poly2nb(x, queen = FALSE)}). + +This function needs the \strong{GRASS} addon \code{v.neighborhoodmatrix}. If it is not installed, it will try to install it. +} +\examples{ +if (grassStarted()) { + +# Setup +library(sf) + +# Polygons vector: +madCoast4 <- fastData(madCoast4) +mc4 <- fast(madCoast4) + +neighs <- neighborhoodMatrix(mc4) +neighs + +} +} diff --git a/man/pcs.Rd b/man/pcs.Rd index bfedd09c..f1322378 100644 --- a/man/pcs.Rd +++ b/man/pcs.Rd @@ -41,5 +41,5 @@ plot(prinComp) } } \seealso{ -\code{\link[=princomp]{princomp()}}, \code{\link[terra:princomp]{terra::princomp()}}, module \code{i.pca} in \strong{GRASS} +\code{\link[=princomp]{princomp()}}, \code{\link[terra:princomp]{terra::princomp()}}, tool \code{i.pca} in \strong{GRASS} } diff --git a/man/project.Rd b/man/project.Rd index 60d34177..b9066e1a 100644 --- a/man/project.Rd +++ b/man/project.Rd @@ -70,7 +70,7 @@ A \code{GRaster} or \code{GVector}. } } \details{ -When projecting a raster, the "fallback" methods in \strong{GRASS} module \code{r.import} are actually used, even though the \code{method} argument takes the strings specifying non-fallback methods. See the manual page for the \code{r.import} \strong{GRASS} module. +When projecting a raster, the "fallback" methods in \strong{GRASS} tool \code{r.import} are actually used, even though the \code{method} argument takes the strings specifying non-fallback methods. See the manual page for the \code{r.import} \strong{GRASS} tool. } \examples{ if (grassStarted()) { diff --git a/man/rSpatialDepRast.Rd b/man/rSpatialDepRast.Rd index 5d5b044d..2b0d4c6e 100644 --- a/man/rSpatialDepRast.Rd +++ b/man/rSpatialDepRast.Rd @@ -35,7 +35,7 @@ A \code{GRaster}. } \description{ -\code{rSpatialDepRast()} creates a raster with random values in cells. Across the raster, values are approximately normally distributed, though a raster with a "true" normal distribution can be made with \code{\link[=rnormRast]{rnormRast()}}. Spatial dependence can be introduced, though all together the values will still be approximately normally distributed. +\code{rSpatialDepRast()} creates a raster with random values in cells. Across the raster, values are approximately normally distributed, though a raster with a "true" normal distribution can be made with \code{\link[=rNormRast]{rNormRast()}}. Spatial dependence can be introduced, though all together the values will still be approximately normally distributed. } \examples{ if (grassStarted()) { @@ -51,11 +51,11 @@ madElev <- fastData("madElev") elev <- fast(madElev) ### Create a raster with values drawn from a uniform distribution: -unif <- runifRast(elev) +unif <- rUnifRast(elev) plot(unif) ### Create a raster with values drawn from a normal distribution: -norms <- rnormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) plot(norms) hist(norms, bins = 100) @@ -74,8 +74,27 @@ fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) plot(fractal) hist(fractal) +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + } } \seealso{ -\code{\link[=rnormRast]{rnormRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \code{\link[=runifRast]{runifRast()}}, \strong{GRASS} manual page for module \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) +\code{\link[=rNormRast]{rNormRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \code{\link[=rUnifRast]{rUnifRast()}}, \code{\link[=rWalkRast]{rWalkRast()}}, \strong{GRASS} manual page for tool \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) } diff --git a/man/rWalkRast.Rd b/man/rWalkRast.Rd new file mode 100644 index 00000000..8cf93f69 --- /dev/null +++ b/man/rWalkRast.Rd @@ -0,0 +1,105 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/rWalkRast.r +\name{rWalkRast,GRaster-method} +\alias{rWalkRast,GRaster-method} +\alias{rWalkRast} +\title{Create raster representing one or more random walks} +\usage{ +\S4method{rWalkRast}{GRaster}( + x, + n = 1, + steps = 1e+05, + directions = 8, + avoid = FALSE, + sameStart = FALSE, + seed = NULL, + check = TRUE +) +} +\arguments{ +\item{x}{A \code{GRaster} to serve as a template.} + +\item{n}{Numeric: Number of walkers. Default is 1.} + +\item{steps}{Numeric: Number of steps taken by each walker. Default is 100000.} + +\item{directions}{Either 4 or 8: Directions in which a walker can turn at any point. If 4, then walks are confined to north/south/east/west directions (Rook's case). If 8, then the cardinal and subcardinal directions are allowed (Queen's case).} + +\item{avoid}{Logical: If \code{FALSE} (default), then walkers can traverse their own walks. If \code{TRUE}, walkers avoid their own trails. A self-avoiding random walk can take much longer to compute.} + +\item{sameStart}{Logical: If \code{FALSE} (default), walkers can begin anywhere. If \code{TRUE}, then walkers start from the same place.} + +\item{seed}{Integer or \code{NULL} (default): If \code{NULL}, then a random seed is generated by the function. If numeric, results will be deterministic. In either case, the value will be rounded to the nearest integer.} + +\item{check}{Logical: If \code{TRUE} (default), function will check to see if the addon \code{r.random.walk} has been installed. If it has not, it will attempt to install it.} +} +\value{ +A \code{GRaster} with cell values representing the number of times one or more walkers traversed the cell. +} +\description{ +This function creates a raster where the cell values represent the number of times one or more random "walkers" traverse the cell. If you simulate multiple random walkers, you can do computation in parallel, which can be controlled by allowing \strong{fasterRaster} to use multiple cores and more memory using the "cores" and "memory" arguments in the \code{\link[=faster]{faster()}} function. +} +\details{ +This function needs the \strong{GRASS} addon \code{r.random.walk}. If it is not installed, it will try to install it.#' +} +\examples{ +if (grassStarted()) { + +# Setup +library(sf) +library(terra) + +# Elevation raster +madElev <- fastData("madElev") + +# Convert a SpatRaster to a GRaster: +elev <- fast(madElev) + +### Create a raster with values drawn from a uniform distribution: +unif <- rUnifRast(elev) +plot(unif) + +### Create a raster with values drawn from a normal distribution: +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +plot(norms) +hist(norms, bins = 100) + +# Create a raster with random, seemingly normally-distributed values: +rand <- rSpatialDepRast(elev, dist = 1000) +plot(rand) + +# Values appear normal on first inspection: +hist(rand) + +# ... but actually are patterned: +hist(rand, bins = 100) + +# Create a fractal raster: +fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) +plot(fractal) +hist(fractal) + +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + +} +} +\seealso{ +\code{\link[=rNormRast]{rNormRast()}}, \code{\link[=rUnifRast]{rUnifRast()}}, \code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=fractalRast]{fractalRast()}} +} diff --git a/man/rasterize.Rd b/man/rasterize.Rd index 483cbd8a..c5ddae59 100644 --- a/man/rasterize.Rd +++ b/man/rasterize.Rd @@ -69,5 +69,5 @@ plot(byRiver) } } \seealso{ -\code{\link[terra:rasterize]{terra::rasterize()}}, \strong{GRASS} module \code{v.to.rast} (see \code{grassHelp("v.to.rast")}) +\code{\link[terra:rasterize]{terra::rasterize()}}, \strong{GRASS} tool \code{v.to.rast} (see \code{grassHelp("v.to.rast")}) } diff --git a/man/replace_dollar.Rd b/man/replace_dollar.Rd index 165aeb9e..8accab7a 100644 --- a/man/replace_dollar.Rd +++ b/man/replace_dollar.Rd @@ -95,6 +95,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -103,14 +104,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -119,9 +126,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/replace_double_square_brackets.Rd b/man/replace_double_square_brackets.Rd index 1b9ebff8..8ffc6b9a 100644 --- a/man/replace_double_square_brackets.Rd +++ b/man/replace_double_square_brackets.Rd @@ -89,6 +89,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -97,14 +98,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -113,9 +120,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/replace_single_square_bracket.Rd b/man/replace_single_square_bracket.Rd index 0f7410c2..545be31b 100644 --- a/man/replace_single_square_bracket.Rd +++ b/man/replace_single_square_bracket.Rd @@ -97,6 +97,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -105,14 +106,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -121,9 +128,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/rnormRast.Rd b/man/rnormRast.Rd index f6833eab..7479ec0c 100644 --- a/man/rnormRast.Rd +++ b/man/rnormRast.Rd @@ -1,11 +1,11 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/rnormRast.r -\name{rnormRast,GRaster-method} -\alias{rnormRast,GRaster-method} -\alias{rnormRast} +% Please edit documentation in R/rNormRast.r +\name{rNormRast,GRaster-method} +\alias{rNormRast,GRaster-method} +\alias{rNormRast} \title{Create a raster with random values drawn from a normal distribution} \usage{ -\S4method{rnormRast}{GRaster}(x, n = 1, mu = 0, sigma = 1, seed = NULL) +\S4method{rNormRast}{GRaster}(x, n = 1, mu = 0, sigma = 1, seed = NULL) } \arguments{ \item{x}{A \code{GRaster}: The output will have the same extent and dimensions as this raster.} @@ -20,7 +20,7 @@ A \code{GRaster}. } \description{ -\code{rnormRast()} creates a raster with values drawn from a normal distribution. +\code{rNormRast()} creates a raster with values drawn from a normal distribution. } \examples{ if (grassStarted()) { @@ -36,11 +36,11 @@ madElev <- fastData("madElev") elev <- fast(madElev) ### Create a raster with values drawn from a uniform distribution: -unif <- runifRast(elev) +unif <- rUnifRast(elev) plot(unif) ### Create a raster with values drawn from a normal distribution: -norms <- rnormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) plot(norms) hist(norms, bins = 100) @@ -59,8 +59,27 @@ fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) plot(fractal) hist(fractal) +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + } } \seealso{ -\code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \code{\link[=runifRast]{runifRast()}}, \strong{GRASS} manual page for module \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) +\code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \code{\link[=rUnifRast]{rUnifRast()}}, \code{\link[=rWalkRast]{rWalkRast()}}, \strong{GRASS} manual page for tool \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) } diff --git a/man/ruggedness.Rd b/man/ruggedness.Rd index 51e3ceac..6969e063 100644 --- a/man/ruggedness.Rd +++ b/man/ruggedness.Rd @@ -5,16 +5,22 @@ \alias{ruggedness} \title{Terrain ruggedness index} \usage{ -\S4method{ruggedness}{GRaster}(x) +\S4method{ruggedness}{GRaster}(x, size = 3, exponent = 0) } \arguments{ \item{x}{A \code{GRaster}.} + +\item{size}{Integer (default is 3): Size of the moving window. Must be an odd integer >= 3.} + +\item{exponent}{Numeric >= 0 and <= 4. Used to reduce the influence of cells farther from the focal cell (larger areas can yield noisier results if the exponent small). All cells are weighted equally when \code{exponent = 0}.} } \value{ A \code{GRaster}. } \description{ -For a given focal grid cell, the terrain ruggedness index (TRI) is calculated by taking the square root of the average of the squared difference between the focal cell's elevation and the elevations of the 8 surrounding cells, or \deqn{\sqrt(\sum_{i = 1}^{8}(m_i - m_0)^2 / 8)} where \eqn{m_0} is the elevation of the focal cell and \eqn{m_i} is the elevation of the \emph{i}th grid cell. +For a given focal grid cell, the terrain ruggedness index (TRI) is calculated by taking the square root of the average of the squared difference between the focal cell's elevation and the elevations of the 8 surrounding cells, or \deqn{\sqrt(\sum_{i = 1}^{8}(m_i - m_0)^2 / 8)} where \eqn{m_0} is the elevation of the focal cell and \eqn{m_i} is the elevation of the \emph{i}th grid cell. Areas that are entirely flat will have a value of \code{NA} assigned to them. + +By default, TRI is calculated for a 3x3 moving window around each focal cell. However, you can use a larger-sized window. In this case, the window size must be an odd number >= 3, and you must have the \code{r.tri} \strong{GRASS} addon installed. If it is not installed, the function will try to install it. } \examples{ if (grassStarted()) { @@ -28,14 +34,20 @@ madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) -# Terrain ruggedness index: -tri <- ruggedness(elev) -plot(c(elev, tri)) - # Topographic wetness index: twi <- wetness(elev) +names(twi) <- 'TWI' plot(c(elev, twi)) +# Terrain ruggedness index: +tri <- ruggedness(elev) +tri7 <- ruggedness(elev, size = 7) +triSmooth7 <- ruggedness(elev, size = 7, exponent = 4) + +tris <- c(elev, tri, tri7, triSmooth7) +names(tris) <- c("elevation", "TRI in 3x3", "TRI in 7x7", "Smoothed TRIin 7x7") +plot(tris) + } } \references{ diff --git a/man/runifRast.Rd b/man/runifRast.Rd index 8d7d58ec..02063c84 100644 --- a/man/runifRast.Rd +++ b/man/runifRast.Rd @@ -1,11 +1,11 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/runifRast.r -\name{runifRast,GRaster-method} -\alias{runifRast,GRaster-method} -\alias{runifRast} +% Please edit documentation in R/rUnifRast.r +\name{rUnifRast,GRaster-method} +\alias{rUnifRast,GRaster-method} +\alias{rUnifRast} \title{Create a raster with random values drawn from a uniform distribution} \usage{ -\S4method{runifRast}{GRaster}(x, n = 1, low = 0, high = 1, seed = NULL) +\S4method{rUnifRast}{GRaster}(x, n = 1, low = 0, high = 1, seed = NULL) } \arguments{ \item{x}{A \code{GRaster}. The output will have the same extent and dimensions as this raster.} @@ -20,7 +20,7 @@ A \code{GRaster}. } \description{ -\code{runifRast()} creates a raster with values drawn from a uniform (flat) distribution. +\code{rUnifRast()} creates a raster with values drawn from a uniform (flat) distribution. } \examples{ if (grassStarted()) { @@ -36,11 +36,11 @@ madElev <- fastData("madElev") elev <- fast(madElev) ### Create a raster with values drawn from a uniform distribution: -unif <- runifRast(elev) +unif <- rUnifRast(elev) plot(unif) ### Create a raster with values drawn from a normal distribution: -norms <- rnormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) +norms <- rNormRast(elev, n = 2, mu = c(5, 10), sigma = c(2, 1)) plot(norms) hist(norms, bins = 100) @@ -59,8 +59,27 @@ fractal <- fractalRast(elev, n = 2, dimension = c(2.1, 2.8)) plot(fractal) hist(fractal) +### Random walker rasters + +# One random walker +walk <- rWalkRast(elev) +plot(walk) + +# Random walker with self-avoidance: +walkAvoid <- rWalkRast(elev, steps = 1000, avoid = TRUE, seed = 1) +plot(walkAvoid) + +# 10 random walkers: +walk10 <- rWalkRast(elev, n = 10) +plot(walk10) + +# 10 random walkers starting in same place: +walkSame10 <- rWalkRast(elev, n = 10, sameStart = TRUE) +plot(walkSame10) + + } } \seealso{ -\code{\link[=rnormRast]{rnormRast()}}, \code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \strong{GRASS} manual page for module \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) +\code{\link[=rNormRast]{rNormRast()}}, \code{\link[=rSpatialDepRast]{rSpatialDepRast()}}, \code{\link[=fractalRast]{fractalRast()}}, \code{\link[=rWalkRast]{rWalkRast()}}, \strong{GRASS} manual page for tool \code{r.random.surface} (see \code{grassHelp("r.random.surface")}) } diff --git a/man/sampleRast.Rd b/man/sampleRast.Rd index 3a9c1731..3e14c583 100644 --- a/man/sampleRast.Rd +++ b/man/sampleRast.Rd @@ -111,5 +111,5 @@ plot(randAll) } } \seealso{ -\code{\link[=spatSample]{spatSample()}}; \code{\link[terra:sample]{terra::spatSample()}}, module \code{r.random} in \strong{GRASS} +\code{\link[=spatSample]{spatSample()}}; \code{\link[terra:sample]{terra::spatSample()}}, tool \code{r.random} in \strong{GRASS} } diff --git a/man/simplifyGeom.Rd b/man/simplifyGeom.Rd index 13d109ed..12d316d4 100644 --- a/man/simplifyGeom.Rd +++ b/man/simplifyGeom.Rd @@ -107,5 +107,5 @@ legend("bottom", } } \seealso{ -\code{\link[=smoothGeom]{smoothGeom()}}, \link[=breakPolys]{geometry cleaning}, \code{\link[terra:simplify]{terra::simplifyGeom()}}, \strong{GRASS} manual page for module \code{v.generalize} (see \code{grassHelp("v.generalize")}) +\code{\link[=smoothGeom]{smoothGeom()}}, \link[=breakPolys]{geometry cleaning}, \code{\link[terra:simplify]{terra::simplifyGeom()}}, \strong{GRASS} manual page for tool \code{v.generalize} (see \code{grassHelp("v.generalize")}) } diff --git a/man/smoothGeom.Rd b/man/smoothGeom.Rd index 5f4bf076..3b42f25a 100644 --- a/man/smoothGeom.Rd +++ b/man/smoothGeom.Rd @@ -105,5 +105,5 @@ legend("bottom", } } \seealso{ -\code{\link[=simplifyGeom]{simplifyGeom()}}, \code{\link[terra:simplify]{terra::simplifyGeom()}}, \link[=breakPolys]{geometry cleaning}, \strong{GRASS} manual page for module \code{v.generalize} (see \code{grassHelp("v.generalize")}) +\code{\link[=simplifyGeom]{simplifyGeom()}}, \code{\link[terra:simplify]{terra::simplifyGeom()}}, \link[=breakPolys]{geometry cleaning}, \strong{GRASS} manual page for tool \code{v.generalize} (see \code{grassHelp("v.generalize")}) } diff --git a/man/spatSample.Rd b/man/spatSample.Rd index 523531fe..77ea5115 100644 --- a/man/spatSample.Rd +++ b/man/spatSample.Rd @@ -135,5 +135,5 @@ plot(randAll) } } \seealso{ -\code{\link[=sampleRast]{sampleRast()}}, \code{\link[terra:sample]{terra::spatSample()}}, module \code{v.random} in \strong{GRASS} +\code{\link[=sampleRast]{sampleRast()}}, \code{\link[terra:sample]{terra::spatSample()}}, tool \code{v.random} in \strong{GRASS} (see \code{grassHelp("v.random")}) } diff --git a/man/streams.Rd b/man/streams.Rd index 24421c40..fd47c51a 100644 --- a/man/streams.Rd +++ b/man/streams.Rd @@ -34,7 +34,7 @@ A \code{GRaster}. } \description{ -This function estimates the course of streams and rivers from an elevation raster. It is based on the \strong{GRASS} module \code{r.stream.extract}, where more details can be found (see \code{grassHelp("r.stream.extract")}) +This function estimates the course of streams and rivers from an elevation raster. It is based on the \strong{GRASS} tool \code{r.stream.extract}, where more details can be found (see \code{grassHelp("r.stream.extract")}) } \examples{ if (grassStarted()) { @@ -55,5 +55,5 @@ plot(streams) } } \seealso{ -\code{\link[=flow]{flow()}}, \code{\link[=flowPath]{flowPath()}}, \strong{GRASS} manual for module \code{r.stream.extract} (see \code{grassHelp("r.stream.extract")}) +\code{\link[=flow]{flow()}}, \code{\link[=flowPath]{flowPath()}}, \strong{GRASS} manual for tool \code{r.stream.extract} (see \code{grassHelp("r.stream.extract")}) } diff --git a/man/stretch.Rd b/man/stretch.Rd index 3392e5c8..a81d31f1 100644 --- a/man/stretch.Rd +++ b/man/stretch.Rd @@ -67,5 +67,5 @@ fr - tr } } \seealso{ -\code{\link[terra:stretch]{terra::stretch()}} and module \code{r.rescale} in \strong{GRASS} (not used on this function) +\code{\link[terra:stretch]{terra::stretch()}} and tool \code{r.rescale} in \strong{GRASS} (not used on this function) } diff --git a/man/subset.Rd b/man/subset.Rd index 85787a87..abc6e733 100644 --- a/man/subset.Rd +++ b/man/subset.Rd @@ -95,6 +95,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -103,14 +104,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -119,9 +126,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/subset_dollar.Rd b/man/subset_dollar.Rd index fdfb4a24..90c7ae3a 100644 --- a/man/subset_dollar.Rd +++ b/man/subset_dollar.Rd @@ -93,6 +93,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -101,14 +102,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -117,9 +124,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/subset_double_square_brackets.Rd b/man/subset_double_square_brackets.Rd index e3a3352f..607c470f 100644 --- a/man/subset_double_square_brackets.Rd +++ b/man/subset_double_square_brackets.Rd @@ -95,6 +95,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -103,14 +104,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -119,9 +126,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/subset_single_bracket.Rd b/man/subset_single_bracket.Rd index a18be8fb..31f7bd15 100644 --- a/man/subset_single_bracket.Rd +++ b/man/subset_single_bracket.Rd @@ -97,6 +97,7 @@ rasts # example data madDypsis <- fastData("madDypsis") # vector of points +madDypsis <- vect(madDypsis) # Convert SpatVector to GVector dypsis <- fast(madDypsis) @@ -105,14 +106,20 @@ dypsis <- fast(madDypsis) dypsis$species # Returns the column -dypsis[[c("year", "species")]] # Returns a GRaster with these columns +dypsis[[c("year", "species")]] # Returns a GVector with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries -# Subset first three geometries -dypsis[1:3] -dypsis[1:3, "species"] +# Subset three geometries +dypsis[c(1, 4, 10)] + +# Subset three geometries and one column. Note order will always be the same +# in the output and may differ in order from terra subsetting. +dypsis[c(1, 4, 10), "species"] +dypsis[c(10, 4, 1), "species"] # fasterRaster: Same order as previous. +madDypsis[c(1, 4, 10), "species"] +madDypsis[c(10, 4, 1), "species"] # terra: different order as previous. # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] @@ -121,9 +128,11 @@ dypsis[dypsis$species == "Dypsis betsimisarakae"] # New column dypsis$pi <- pi +head(dypsis) # Re-assign values dypsis$pi <- "pie" +head(dypsis) # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- diff --git a/man/sun.Rd b/man/sun.Rd index 6135cb90..223ea8f6 100644 --- a/man/sun.Rd +++ b/man/sun.Rd @@ -46,7 +46,7 @@ sun( \item{albedo}{A \code{GRaster} or a numeric value: This is either a raster with values of ground albedo or a numeric value (in which case albedo is assumed to be the same everywhere). Albedo is unit-less, and the default value is 0.2.} -\item{linke}{A \code{GRaster} or a numeric value: This is either a raster with values of the Linke atmospheric turbidity coefficient or a numeric value (in which case the same value is assumed for all locations). The Linke coefficient is unit-less. The default value is 3, but see also the \strong{GRASS} manual page for module \code{r.sun} (\code{grassHelp("r.sun")}).} +\item{linke}{A \code{GRaster} or a numeric value: This is either a raster with values of the Linke atmospheric turbidity coefficient or a numeric value (in which case the same value is assumed for all locations). The Linke coefficient is unit-less. The default value is 3, but see also the \strong{GRASS} manual page for tool \code{r.sun} (\code{grassHelp("r.sun")}).} \item{day}{Positive integer between 1 to 365, inclusive: Day of year for which to calculate ir/radiation. Default is 1 (January 1st).} @@ -60,17 +60,17 @@ sun( \item{npartitions}{Positive numeric. Number of chunks in which to read input files. Default is 1.} -\item{beam_rad}{Logical: If \code{TRUE} (default), generate a raster with beam irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} module).} +\item{beam_rad}{Logical: If \code{TRUE} (default), generate a raster with beam irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} tool).} \item{diff_rad}{Logical: If \code{TRUE} (default), generate a raster representing irradiation in Wh / m^2 /day} -\item{refl_rad}{Logical: If \code{TRUE} (default), generate a raster with ground-reflected irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} module).} +\item{refl_rad}{Logical: If \code{TRUE} (default), generate a raster with ground-reflected irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} tool).} -\item{glob_rad}{Logical:. If \code{TRUE} (default), generate a raster with total irradiance/irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} module).} +\item{glob_rad}{Logical:. If \code{TRUE} (default), generate a raster with total irradiance/irradiation with units of Wh / m^2 / day ("mode 2" of the \code{r.sun} \strong{GRASS} tool).} -\item{insol_time}{Logical: If \code{TRUE} (default), generate a raster with total insolation time in hours ("mode 2" of the \code{r.sun} \strong{GRASS} module).} +\item{insol_time}{Logical: If \code{TRUE} (default), generate a raster with total insolation time in hours ("mode 2" of the \code{r.sun} \strong{GRASS} tool).} -\item{lowMemory}{Logical: If \code{TRUE}, use the low-memory version of the \code{r.sun} \strong{GRASS} module. The default is \code{FALSE}.} +\item{lowMemory}{Logical: If \code{TRUE}, use the low-memory version of the \code{r.sun} \strong{GRASS} tool. The default is \code{FALSE}.} } \value{ A raster or raster stack stack with the same extent, resolution, and coordinate reference system as \code{elevation}. Assuming all possible rasters are generated they represent: @@ -83,7 +83,7 @@ A raster or raster stack stack with the same extent, resolution, and coordinate } } \description{ -The \code{sun()} function calculates beam (direct), diffuse and ground reflected solar irradiation for a given day and set of topographic and atmospheric conditions. The function relies on the \strong{GRASS} module \code{r.sun}, the manual page for which contains a detailed explanation (see \code{grassHelp("r.sun")}) +The \code{sun()} function calculates beam (direct), diffuse and ground reflected solar irradiation for a given day and set of topographic and atmospheric conditions. The function relies on the \strong{GRASS} tool \code{r.sun}, the manual page for which contains a detailed explanation (see \code{grassHelp("r.sun")}) } \examples{ if (grassStarted()) { @@ -144,5 +144,5 @@ solar } } \seealso{ -\code{\link[=terrain]{terrain()}}, \code{\link[=horizonHeight]{horizonHeight()}}, \strong{GRASS} manual page for module \code{r.sun} (see \code{grassHelp("r.sun")}) +\code{\link[=terrain]{terrain()}}, \code{\link[=horizonHeight]{horizonHeight()}}, \strong{GRASS} manual page for tool \code{r.sun} (see \code{grassHelp("r.sun")}) } diff --git a/man/terrain.Rd b/man/terrain.Rd index 8e73a9bb..e8ea9b66 100644 --- a/man/terrain.Rd +++ b/man/terrain.Rd @@ -67,5 +67,5 @@ plot(hs) } } \seealso{ -\code{\link[terra:terrain]{terra::terrain()}}, \code{\link[=ruggedness]{ruggedness()}}, \code{\link[=wetness]{wetness()}}, \code{\link[=geomorphons]{geomorphons()}}, module \code{r.slope.aspect} in \strong{GRASS} +\code{\link[terra:terrain]{terra::terrain()}}, \code{\link[=ruggedness]{ruggedness()}}, \code{\link[=wetness]{wetness()}}, \code{\link[=geomorphons]{geomorphons()}}, tool \code{r.slope.aspect} in \strong{GRASS} } diff --git a/man/thinLines.Rd b/man/thinLines.Rd index a9ba0fd8..cb32b3c8 100644 --- a/man/thinLines.Rd +++ b/man/thinLines.Rd @@ -46,5 +46,5 @@ plot(cleanLines, add = TRUE) } } \seealso{ -\code{\link[=as.lines]{as.lines()}}, \strong{GRASS} manual page for module \code{r.thin} (see \code{grassHelp("r.thin")}) +\code{\link[=as.lines]{as.lines()}}, \strong{GRASS} manual page for tool \code{r.thin} (see \code{grassHelp("r.thin")}) } diff --git a/man/trim.Rd b/man/trim.Rd index 7b39d4c9..877a8221 100644 --- a/man/trim.Rd +++ b/man/trim.Rd @@ -59,5 +59,5 @@ dim(trimmedElevs) } } \seealso{ -\code{\link[terra:trim]{terra::trim()}}, \code{\link[=extend]{extend()}}, and \strong{GRASS} module \code{g.region} +\code{\link[terra:trim]{terra::trim()}}, \code{\link[=extend]{extend()}}, and \strong{GRASS} tool \code{g.region} } diff --git a/man/vegIndex.Rd b/man/vegIndex.Rd index 15b2d4c2..567c0ba8 100644 --- a/man/vegIndex.Rd +++ b/man/vegIndex.Rd @@ -75,5 +75,5 @@ plot(rnir) } } \seealso{ -\strong{GRASS} manual page for module \code{i.vi} (see \code{grassHelp("i.vi")}) +\strong{GRASS} manual page for tool \code{i.vi} (see \code{grassHelp("i.vi")}) } diff --git a/man/voronoi.Rd b/man/voronoi.Rd index 91a28f0c..4e9dc059 100644 --- a/man/voronoi.Rd +++ b/man/voronoi.Rd @@ -50,5 +50,5 @@ plot(rand) } } \seealso{ -\code{\link[terra:voronoi]{terra::voronoi()}}, \code{\link[sf:geos_unary]{sf::st_voronoi()}}, module \code{v.voronoi} in \strong{GRASS} +\code{\link[terra:voronoi]{terra::voronoi()}}, \code{\link[sf:geos_unary]{sf::st_voronoi()}}, tool \code{v.voronoi} in \strong{GRASS} } diff --git a/man/wetness.Rd b/man/wetness.Rd index 6c550b58..385ccda3 100644 --- a/man/wetness.Rd +++ b/man/wetness.Rd @@ -28,16 +28,22 @@ madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) -# Terrain ruggedness index: -tri <- ruggedness(elev) -plot(c(elev, tri)) - # Topographic wetness index: twi <- wetness(elev) +names(twi) <- 'TWI' plot(c(elev, twi)) +# Terrain ruggedness index: +tri <- ruggedness(elev) +tri7 <- ruggedness(elev, size = 7) +triSmooth7 <- ruggedness(elev, size = 7, exponent = 4) + +tris <- c(elev, tri, tri7, triSmooth7) +names(tris) <- c("elevation", "TRI in 3x3", "TRI in 7x7", "Smoothed TRIin 7x7") +plot(tris) + } } \seealso{ -\code{\link[=terrain]{terrain()}}, \code{\link[=ruggedness]{ruggedness()}}, \code{\link[=geomorphons]{geomorphons()}}, \strong{GRASS} manual for module \code{r.topidx} (see \code{grassHelp("r.topidx")}) +\code{\link[=terrain]{terrain()}}, \code{\link[=ruggedness]{ruggedness()}}, \code{\link[=geomorphons]{geomorphons()}}, \strong{GRASS} manual for tool \code{r.topidx} (see \code{grassHelp("r.topidx")}) } diff --git a/man/workDir.Rd b/man/workDir.Rd index 113e9550..8f1e95d7 100644 --- a/man/workDir.Rd +++ b/man/workDir.Rd @@ -3,12 +3,15 @@ \name{.workDir,GLocation-method} \alias{.workDir,GLocation-method} \alias{.workDir} +\alias{.workDir,missing-method} \title{Get a GLocation's working directory} \usage{ \S4method{.workDir}{GLocation}(x) + +\S4method{.workDir}{missing}(x) } \arguments{ -\item{x}{A \code{GLocation} object.} +\item{x}{A \code{GLocation} object or missing. If an object, returns the working folder in which the object is saved by \strong{GRASS}. If missing, then just returns the working folder (same as \code{faster("workDir")}).} } \value{ Character. diff --git a/man/writeRaster.Rd b/man/writeRaster.Rd index 54d79c23..f972d0ab 100644 --- a/man/writeRaster.Rd +++ b/man/writeRaster.Rd @@ -68,7 +68,7 @@ \item{...}{Additional arguments. These can include: \itemize{ \item \code{bigTiff}: Logical: If \code{TRUE}, and the file format is a GeoTIFF and would be larger than 4 GB (regardless of compression), then the file will be saved in BIGTIFF format. -\item \code{format}: Character, indicating file format. This is usually ascertained from the file extension, but in case this fails, it can be stated explicitly. When using other formats, you may have to specify the \code{createopts} argument, too (see help page for \strong{GRASS} module \code{r.out.gdal}). Two common formats include: +\item \code{format}: Character, indicating file format. This is usually ascertained from the file extension, but in case this fails, it can be stated explicitly. When using other formats, you may have to specify the \code{createopts} argument, too (see help page for \strong{GRASS} tool \code{r.out.gdal}). Two common formats include: \itemize{ \item \code{"GTiff"} (default): GeoTIFF \code{filename} ends in \code{.tif}. \item \code{"ASC"}: ASCII \code{filename} ends in \code{.asc} @@ -83,7 +83,7 @@ A \code{GRaster} (invisibly). A raster is also saved to disk. \description{ This function saves a \code{GRaster} to disk directly from a \strong{GRASS} session. It is faster than using \code{\link[=rast]{rast()}}, then saving the output of that to disk (because \code{rast()} actually save the raster to disk, anyway). -The function will attempt to ascertain the file type to be ascertained from the file extension, but you can specify the format using the \code{format} argument (see entry for \code{...}). You can see a list of supported formats by simply using this function with no arguments, as in \code{writeRaster()}, or by consulting the online help page for the \strong{GRASS} module \code{r.out.gdal} (see \code{grassHelp("r.out.gdal")}). Only the \code{GeoTIFF} file format is guaranteed to work for multi-layered rasters. +The function will attempt to ascertain the file type to be ascertained from the file extension, but you can specify the format using the \code{format} argument (see entry for \code{...}). You can see a list of supported formats by simply using this function with no arguments, as in \code{writeRaster()}, or by consulting the online help page for the \strong{GRASS} tool \code{r.out.gdal} (see \code{grassHelp("r.out.gdal")}). Only the \code{GeoTIFF} file format is guaranteed to work for multi-layered rasters. The function will attempt to optimize the \code{datatype} argument, but this can take a long time. You can speed this up by setting \code{datatype} manually. Note that if you are saving a "stack" of \code{GRaster}s with different \code{datatype}s, the one with the highest information density will be used (e.g., low-bit integer < high-bit integer < floating-point < double-floating point). This can make rasters with lower datatypes much larger on disk. In these cases, it make be best to save rasters with similar \code{datatype}s together. } @@ -131,5 +131,5 @@ chelsaBio1 } } \seealso{ -\code{\link[terra:writeRaster]{terra::writeRaster()}}, \strong{GRASS} module \code{r.out.gdal} (see \code{grassHelp("r.out.gdal")}) +\code{\link[terra:writeRaster]{terra::writeRaster()}}, \strong{GRASS} tool \code{r.out.gdal} (see \code{grassHelp("r.out.gdal")}) } diff --git a/man/writeVector.Rd b/man/writeVector.Rd index 8d7fecbb..0816f4bc 100644 --- a/man/writeVector.Rd +++ b/man/writeVector.Rd @@ -37,7 +37,7 @@ \item{attachTable}{Logical: If \code{TRUE} (default), attach the attribute to table to the vector before saving it. If \code{FALSE}, the attribute table will not be attached.} -\item{...}{Additional arguments to send to \strong{GRASS} module \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}).} +\item{...}{Additional arguments to send to \strong{GRASS} tool \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}).} } \value{ Invisibly returns a \code{GRaster} (the input, \code{x}). Also saves the vector to disk. @@ -45,7 +45,7 @@ Invisibly returns a \code{GRaster} (the input, \code{x}). Also saves the vector \description{ This function saves a \code{GVector} to disk directly from a \strong{GRASS} session. -By default, files will be of OGC GeoPackage format (extension "\code{.gpkg}"), but this can be changed with the \code{format} argument. You can see a list of supported formats by simply using this function with no arguments, as in \code{writeVector()}, or by consulting the online help page for \strong{GRASS} module \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}). +By default, files will be of OGC GeoPackage format (extension "\code{.gpkg}"), but this can be changed with the \code{format} argument. You can see a list of supported formats by simply using this function with no arguments, as in \code{writeVector()}, or by consulting the online help page for \strong{GRASS} tool \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}). Note that if the vector has a data table attached and at least one numeric or integer column has an \code{NA} or \code{NaN} value, the function will yield a warning like: @@ -97,7 +97,7 @@ writeVector(rivers, filename) } } \seealso{ -\code{\link[terra:writeVector]{terra::writeVector()}}, \code{\link[sf:st_write]{sf::st_write()}}, \strong{GRASS} module \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}) +\code{\link[terra:writeVector]{terra::writeVector()}}, \code{\link[sf:st_write]{sf::st_write()}}, \strong{GRASS} tool \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}) -\code{\link[terra:writeVector]{terra::writeVector()}}, the \strong{GRASS} module manual page for \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}) +\code{\link[terra:writeVector]{terra::writeVector()}}, the \strong{GRASS} tool manual page for \code{v.out.ogr} (see \code{grassHelp("v.out.ogr")}) } diff --git a/vignettes/addons.Rmd b/vignettes/addons.Rmd deleted file mode 100644 index 1e58fc2b..00000000 --- a/vignettes/addons.Rmd +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: "fasterRaster addons" -output: rmarkdown::html_vignette -author: "Adam B. Smith" -date: "`r Sys.Date()`" -vignette: > - %\VignetteIndexEntry{fasterRaster addons} - %\VignetteEngine{knitr::rmarkdown} - %\VignetteEncoding{UTF-8} ---- - -```{r, include = FALSE} -knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>" -) -fig.path = 'man/figures/' -``` -**GRASS GIS** comes with a default set of modules (functions), but users can download and install "addon" modules to extend its capabilities. Some of the functions in **fasterRaster** rely on these addon modules. To make these functions work, you must find the folder in which addons are stored and install the desired module. - -1. Installing modules: The easiest (only?) way to do this is to start **GRASS** (not in **R** through **fasterRaster**, but actually start **GRASS**), then use the `Settings` menu's `Addon extensions` option, then select `Install extensions from addons [g.extension]`. **GRASS** should display a list of addons you can install. - -2. Once you have the desired extension(s) installed, you can use **fasterRaster** functions that call them. To do this, you need to specify the `addons` folder *before* starting **GRASS** (i.e., before the first time you use the `fast()` function to load a raster or vector). Use `faster()` to tell **fasterRaster** where this folder is. The folder will vary by operating system. On a Windows machine, it will be something like: - -``` -C:/Users/your_windows_user_name/AppData/Roaming/GRASS8/addons -``` - -You can set the addons folder using `faster(addonsDir = "C:/Users/your_windows_user_name/AppData/Roaming/GRASS8/addons")`. - -## Validating addons -You can test to see if the `addons` folder is correct using `addons()`. You can also see if a particular addon module was installed correctly using the same function using, for example, `addons("v.centerpoint")`. - -## **fasterRaster** functions that need addons -These functions must have the specified addon to work. - - | **Function** | **addon** | - | --------------------------|--------------------| - | `centroids()` | `v.centerpoint` | - - - -~ FINIS ~ diff --git a/vignettes/fasterRaster.Rmd b/vignettes/fasterRaster.Rmd index 0a707430..696ac135 100644 --- a/vignettes/fasterRaster.Rmd +++ b/vignettes/fasterRaster.Rmd @@ -19,7 +19,7 @@ knitr::opts_chunk$set( ) fig.path = 'man/figures/' ``` -**fasterRaster** interfaces with **GRASS GIS** to process rasters and spatial vector data. It is intended as an add-on to the **terra** and **sf** packages, and relies heavily upon them. For most rasters and vectors that are small or medium-sized in memory/disk, those packages will almost always be faster. They may also be faster for very large objects. But when they aren't, **fasterRaster** can step in. +**fasterRaster** interfaces with **GRASS** to process rasters and spatial vector data. It is intended as an add-on to the **terra** and **sf** packages, and relies heavily upon them. For most rasters and vectors that are small or medium-sized in memory/disk, those packages will almost always be faster. They may also be faster for very large objects. But when they aren't, **fasterRaster** can step in. ## Installing **fasterRaster** @@ -27,15 +27,15 @@ You probably already have **fasterRaster** installed on your computer, but if no ```{r install, eval = FALSE} install.packages("fasterRaster") ``` -and the latest development version using: +or the latest development version using: ```{r install_dev, eval = FALSE} remotes::install_github("adamlilith/fasterRaster", dependencies = TRUE) ``` (You may need to install the `remotes` package first.) -## Installing **GRASS GIS** +## Installing **GRASS** -**fasterRaster** uses **GRASS** to do its operations. You will need to install **GRASS** using the "stand-alone" installer, available through the [GRASS GIS](https://grass.osgeo.org/). *Be sure to use the "stand-alone" installer, not the "OSGeo4W" installer!* +**fasterRaster** uses **GRASS** to do its operations. You will need to install **GRASS** using the "stand-alone" installer, available through the [GRASS](https://grass.osgeo.org/). *Be sure to use the "stand-alone" installer, not the "OSGeo4W" installer!* Optional: A few functions in **fasterRaster** require **GRASS** "addon" modules, which do not come bundled with **GRASS**. You do not need to install these addons if you do not use functions that call them. A list of functions that require addons can be seen in the "addons" vignette (in **R**, use `vignette("addons", package = "fasterRaster")`). This vignette also explains how to install addons. @@ -51,12 +51,12 @@ library(fasterRaster) To begin, you need to tell **fasterRaster** the full file path of the folder where **GRASS** is installed on your system. Where this is well depend on your operating system and the version of **GRASS** installed. Three examples below show you what this might look like, but you may need to change the file path to match your case: ```{r grassDir_examples, eval = FALSE} -grassDir <- "C:/Program Files/GRASS GIS 8.3" # Windows -grassDir <- "/Applications/GRASS-8.3.app/Contents/Resources" # Mac OS +grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows +grassDir <- "/Applications/GRASS-8.4.app/Contents/Resources" # Mac OS grassDir <- "/usr/local/grass" # Linux ``` ```{r grassDir, echo = FALSE} -grassDir <- "C:/Program Files/GRASS GIS 8.3" # Windows +grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows ``` To tell **fasterRaster** where **GRASS** is installed, use the `faster()` function: diff --git a/vignettes/hidden_functions.Rmd b/vignettes/hidden_functions.Rmd index 99c360f7..66832b7d 100644 --- a/vignettes/hidden_functions.Rmd +++ b/vignettes/hidden_functions.Rmd @@ -20,7 +20,8 @@ fig.path = 'man/figures/' **fasterRaster** contains a set of "private" functions that users can access using `fasterRaster:::functionName`. These functions are useful for power users and developers. Not all hidden functions are listed here. Often, a method will have a hidden function of the same name that starts with a period (e.g., `.plot()`). This "period" function is intended to be supplied the [`sources()`](https://adamlilith.github.io/fasterRaster/reference/sources.html) name of a `GRaster` or `GVector` from other functions so that the calling function does not need to spend the time creating the `GRaster` or `GVector` pointer before calling the function. "Period" functions will, though, often work on `GRaster`s or `GVector`s, though some error-checking and region re-definition is not conducted. ## General -* `.backdoor()`: Calls [faster()] and sets **GRASS** folder to "C:/Program Files/GRASS GIS X.Y", plus other options useful for development. +* `.addons()`: Tests if an addon is installed, and if not, attempts to install it. +* `.backdoor()`: Calls [faster()] and sets **GRASS** folder to "`C:/Program Files/GRASS GIS X.Y`", plus other options useful for development. * `.fileExt()`: Get file extension * `.ls()`: Lists the `sources` of all objects in the active **GRASS** "project/location" * `.message()`: Display a warning or message if the given warning has not been displayed since **fasterRaster** was attached or if a given number of hours has passed @@ -58,14 +59,14 @@ fig.path = 'man/figures/' * `.minVal()` and `.maxVal()`: Values in the `@minVal` and `@maxVal` slots in a `GRaster` * `.nlevels()`: Number of levels in a `SpatVector`, `data.frame`, `data.table`, empty string, or a list of `data.frame`s, `data.table`s, and/or empty strings. -## **GRASS** "Projects/locations" and "mapsets" +## **GRASS** "projects/locations" and "mapsets" * `.locationCreate()` Make a connection to **GRASS** (i.e., start **GRASS** from within **R**) and create a location * `.locationDelete()` Deletes all files associated with a **GRASS** "location" and mapset * `.locationFind()`: Find a specific **GRASS** "location" that already exists * `.locationRestore()` Reconnect **GRASS** to a previously-created **GRASS** "location" * `.locations()`: List of all available "locations" -* `.g.proj()`: Runs **GRASS** `g.proj` module to display projection of current "project" -* `.g.region()`: Runs **GRASS** `g.region` module to display region of current "project" +* `.g.proj()`: Runs **GRASS** `g.proj` tool to display projection of current "project" +* `.g.region()`: Runs **GRASS** `g.region` tool to display region of current "project" * `.mapset()`: **GRASS** "mapset" of an object or the active session ## **GRASS** "regions" diff --git a/vignettes/projects_mapsets.Rmd b/vignettes/projects_mapsets.Rmd index 02bfb51f..6ac73b48 100644 --- a/vignettes/projects_mapsets.Rmd +++ b/vignettes/projects_mapsets.Rmd @@ -17,7 +17,7 @@ knitr::opts_chunk$set( fig.path = 'man/figures/' ``` -**GRASS GIS** uses "projects" (which used to be called "locations" before **GRASS** 8.4), and "mapsets" to store files (rasters, vectors, etc.). **fasterRaster** uses projects and mapsets, too, but in a manner that is invisibly to most users. Thus, this tutorial is mostly of interest to developers and other curious people. +**GRASS** uses "projects" (which used to be called "locations" before **GRASS** 8.4), and "mapsets" to store files (rasters, vectors, etc.). **fasterRaster** uses projects and mapsets, too, but in a manner that is invisibly to most users. Thus, this tutorial is mostly of interest to developers and other curious people. ## **GRASS** locations/projects Upon starting, **GRASS** creates (or loads) a project, which corresponds to a folder on the user's system. Importantly, all rasters and vectors in a project must have the same coordinate reference system (CRS). Confusingly, rasters and vectors in the same **GRASS** location do not necessarily have to represent the same place on Earth (this the renaming to "project"). In general, rasters and vectors can only interact with one another if they are in the same project and mapset. **GRASS** can only have a connection to a single project at a time. diff --git a/vignettes/regions.Rmd b/vignettes/regions.Rmd index 03df0fbf..494a4779 100644 --- a/vignettes/regions.Rmd +++ b/vignettes/regions.Rmd @@ -16,7 +16,7 @@ knitr::opts_chunk$set( ) fig.path = 'man/figures/' ``` -A **GRASS** *region* is a data structure like a raster in that it is composed of a grid, but different in that "cells" in this grid do not contain values. Rather, their resolution and the extent of the region influence how rasters are imported, created, processed, and exported. In most cases, whenever a raster undergoes one of these processes using a **GRASS** module, the raster will be resampled and/or crop/extend it so that matches the region"s extent and resolution. If ignored, this can cause unintended side effects if the region's geometry doesn't match the raster being processed. +A **GRASS** *region* is a data structure like a raster in that it is composed of a grid, but different in that "cells" in this grid do not contain values. Rather, their resolution and the extent of the region influence how rasters are imported, created, processed, and exported. In most cases, whenever a raster undergoes one of these processes using a **GRASS** tool, the raster will be resampled and/or crop/extend it so that matches the region"s extent and resolution. If ignored, this can cause unintended side effects if the region's geometry doesn't match the raster being processed. Generally, most users of **fasterRaster** will not need to know how regions work because their management is handled automatically. This help page is provided to assist power users who may wish to use regions explicitly or develop their own applications based on **fasterRaster**.