Type: | Package |
Title: | Faster Raster and Spatial Vector Processing Using 'GRASS' |
Version: | 8.4.1.0 |
Date: | 2025-06-19 |
Maintainer: | Adam B. Smith <adam.smith@mobot.org> |
Description: | Processing of large-in-memory/large-on disk rasters and spatial vectors using 'GRASS' https://grass.osgeo.org/. 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' 8.0 or higher. |
Depends: | R (≥ 4.0.0) |
Imports: | data.table (≥ 1.14.8), DT, graphics, grDevices, methods, omnibus (≥ 1.2.15), rgrass (≥ 0.3-9), sf, shiny, terra (≥ 1.7), utils |
Suggests: | knitr, rmarkdown |
License: | GPL (≥ 3) |
SystemRequirements: | GRASS (>= 8) |
URL: | https://github.com/adamlilith/fasterRaster, https://adamlilith.github.io/fasterRaster/ |
BugReports: | https://github.com/adamlilith/fasterRaster/issues |
VignetteBuilder: | knitr |
Encoding: | UTF-8 |
LazyData: | true |
LazyLoad: | yes |
RoxygenNote: | 7.3.2 |
NeedsCompilation: | no |
Packaged: | 2025-06-20 00:17:38 UTC; adame |
Author: | Adam B. Smith |
Repository: | CRAN |
Date/Publication: | 2025-06-20 02:20:02 UTC |
"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. 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")
-
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 aSpatRaster
,SpatVector
, orsf
vector to fasterRaster's raster format (GRaster
s) or vector format (GVector
s), or load one from a file -
rast()
,vect()
, andst_as_sf()
: ConvertGRaster
s andGVector
s toSpatRaster
s,SpatVector
s, orsf
vectors -
writeRaster()
andwriteVector()
: SaveGRaster
s orGVector
s to disk
Properties of GRasters
-
crs()
: Coordinate reference system -
coordRef()
: Coordinate reference system -
datatype()
: Data type -
ext()
,N()
,S()
,E()
,W()
,top()
, andbottom()
: Spatial extent -
freq()
: Frequencies of cell values in a raster -
is.int()
,is.cell()
,is.float()
,is.doub()
:GRaster
data type (integer/float/double) -
is.factor()
: Does a raster represent categorical data? -
is.lonlat()
: Is an object projected (e.g., in WGS84)? -
levels()
: Names of levels in a categoricalGRaster
-
minmax()
: Minimum and maximum values across all non-NA
cells -
names()
:GRaster
names -
ncol()
: Number of columns -
nacell()
: Number ofNA
cells -
ncell()
: Number of cells -
ncell3d()
: Number of cells of a 3DGRaster
-
ndepth()
: Number of depths of a 3DGRaster
-
nlyr()
: Number of layers -
nonnacell()
: Number of non-NA
cells -
nrow()
: Number of rows -
nlevels()
: Number of categories -
res()
,res3d()
,xres()
,yres()
, andzres()
: Spatial resolution -
sources()
: Name of the raster file in the GRASS cache -
topology()
: Dimensionally (2D or 3D) -
zext()
: Vertical extent -
zres()
: Vertical resolution
Functions that operate on or create GRasters
-
Arithmetic: Mathematical operations on
GRaster
s:+
,-
,*
,/
,^
,%%
(modulus),%/%
(integer division) -
Logical comparisons:
<
,<=
,==
,!=
,>=
, and>
, plus%in%
and%notin%
(for categorical rasters only) -
Logical operators:
|
and&
Mathematical functions that are applied to each layer of a GRaster
:
Trigonometry:
sin()
,cos()
,tan()
,asin()
,acos()
,atan()
,atan2()
Logarithms and powers:
exp()
,log()
,ln()
,log1p()
,log2()
,log10()
,sqrt()
Signs:
abs()
Mathematical functions that are applied across layers of multi-layered GRaster
s:
Dispersion:
stdev()
,var()
,varpop()
,nunique()
,range()
,quantile()
,skewness()
,kurtosis()
Extremes:
min()
,max()
,which.min()
,which.max()
Subsetting, assigning, and replacing GRaster
layers
-
$,
[[
, orsubset()
: Subset or remove specific layers of aGRaster
-
[<-
: Replace values of cells of aGRaster
-
[[<-
: Replace specific layers of aGRaster
-
add<-
: Replace specific layers of aGRaster
Operations on GRaster
s
-
as.int()
,as.float()
,as.doub()
: Change data type (integer/float/double) -
as.lines()
: Convert aGRaster
to a "lines" vector -
as.points()
: Convert aGRaster
to a "points" vector -
as.polygons()
: Convert aGRaster
to a "polygons" vector -
aggregate()
: Aggregate values ofGRaster
cells into larger cells -
bioclims()
: BIOCLIM rasters (classic set and extended set) -
buffer()
: Create a buffer around non-NA
cells -
app()
: Apply a user-defined function to multiple layers of aGRaster
(with helper functionsappFuns()
andappCheck()
) -
c()
: "Stack" two or more rasters -
cellSize()
: Cell area -
classify()
: Partition cell values into strata -
clump()
: Group adjacent cells with similar values -
combineLevels()
: Combine the "levels" tables of two or more categoricalGRaster
s -
concats()
: Combine values from two or more categorical and/or integer rasters by concatenating them -
crop()
: Remove parts of aGRaster
-
denoise()
: Remove "noise" from aGRaster
using a principal components analysis (PCA) -
distance()
: Distance to non-NA
cells, or vice versa -
extend()
: Add rows and columns to aGRaster
-
extract()
: Extract values from aGRaster
at locations of aGVector
-
fillNAs()
: FillNA
cells -
focal()
: Calculate cell values based on values of nearby cells -
fragmentation()
: Landscape fragmentation class from Riitters et al. (2020) -
global()
: Summary statistics across cells of eachGRaster
layer -
hist()
: Histogram ofGRaster
values -
interpIDW()
: Interpolate values at points to aGRaster
-
kernel()
: Kernel density estimator of points -
layerCor()
: Correlation or covariance between two or moreGRaster
layers -
mask()
: Remove values in aGRaster
based on values in anotherGRaster
or vector -
maskNA()
: Mask all non-NA cells or all NA cells -
match()
,%in%
, and%notin%
: Find which cells of aGRaster
match or do not match certain values -
merge()
: Combine two or more rasters with different extents and fill inNA
s -
multivarEnvSim()
: Multivariate environmental similarity surface (MESS) -
names<-
: Assign names to aGRaster
-
noise()
: Remove coarse-scale trends from aGRaster
, leaving just fine-scale "noise" -
pairs()
: Plot correlations betweenGRaster
layers -
pcs()
: Retrieve a principal components model from a PCAGRaster
generated usingprincomp()
-
plot()
: Display aGRaster
-
project()
: Change coordinate reference system and cell size -
predict()
: Make predictions to aGRaster
from a linear model or generalized linear model -
princomp()
: Apply a principal components analysis (PCA) to aGRaster
-
regress()
: Regression intercept, slope, r2, and t-value across each set of cells -
resample()
: Change cell size -
reorient()
: Convert degrees between 'north-orientation' and 'east orientation' -
sampleRast()
: Randomly sample cells from aGRaster
-
scale()
,scalepop()
, andunscale()
: Subtract means and divide by standard deviations, or inverse of that -
selectRange()
: Select values from rasters in a stack based on values in anotherGRaster
-
spatSample()
: Randomly points from aGRaster
-
stretch()
: Rescale values in a GRaster -
subst()
: Re-assign cell values -
thinLines()
: Reduce linear features on aGRaster
so linear features are 1 cell wide -
tiles()
: Divide aGRaster
into spatially exclusive subsets (though with possible overlap) -
trim()
: Remove rows and columns from aGRaster
that are allNA
-
zonal()
: Statistics (mean, sum, etc.) on areas of aGRaster
defined by sets of cells with the same values in anotherGRaster
, or by geometries in aGVector
-
zonalGeog()
: Geographic statistics (area, perimeter, fractal dimension, etc.) for sets of cells with the same values
Creating GRaster
s de novo
-
fractalRast()
: Create a fractalGRaster
-
init()
: GRaster with values equal to row, column, coordinate, regular, or "chess" -
longlat()
: Create longitude/latitude rasters -
rNormRast()
: A randomGRaster
with values drawn from a normal distribution -
rSpatialDepRast()
: Create a randomGRaster
with or without spatial dependence -
rUnifRast()
: A randomGRaster
with values drawn from a uniform distribution -
rWalkRast()
: Paths of random walkers -
sineRast()
: Sine wave rasters
Analysis of terrain and hydrology
-
as.contour()
: Contour lines from aGRaster
-
flow()
: Identify watershed basins and direction and accumulation of flow -
flowPath()
: Path of water flow across a landscape -
geomorphons()
: Identify terrain feature types -
hillshade()
: Create a hillshadeGRaster
-
horizonHeight()
: Horizon height -
sun()
: Solar radiance and irradiance -
ruggedness()
: Terrain Ruggedness Index -
streams()
: Create stream network -
terrain()
: Slope, aspect, curvature, and partial slopes -
wetness()
: Topographic wetness index
Operations on categorical (factor) GRaster
s
-
%in%
, and%notin%
: Mask cells that match or do not match a given category -
activeCat()
andactiveCats()
: Column(s) that defines category labelsactiveCat<-
: Set column that defines category labels -
addCats()
: Add new columns to a "levels" tableaddCats<-
: Add new rows (levels) to a "levels" table -
categories()
: Set "levels" table for specific layers of a categorical raster -
catNames()
: Column names of each "levels" table -
cats()
: "Levels" table of a categorical raster -
combineLevels()
: Combine the "levels" tables of two or more categoricalGRaster
s -
complete.cases()
: Find rows of a categoricalGRaster
's "levels" table that have noNA
s in them -
concats()
: Combine categories from two or more categorical rasters by concatenating them -
droplevels()
: Remove one or more levels -
freq()
: Frequency of each category across cells of a raster -
is.factor()
: Is a raster categorical? -
levels()
: "Levels" table of a categorical raster -
levels<-
: Set "levels" table of a categorical raster -
match()
,%in%
, and%notin%
: Find which cells of aGRaster
match or do not match certain category labels -
minmax()
: "Lowest" and "highest" category values of categorical rasters (when argumentlevels = TRUE
) -
missing.cases()
: Find rows of a categoricalGRaster
's "levels" table that have at least oneNA
in them -
missingCats()
: Values that have no category assigned to them -
nlevels()
: Number of levels -
segregate()
: Create one GRaster layer per unique value in a GRaster -
subst()
: Re-assign category levels -
zonalGeog()
: Geographic statistics (area, perimeter, fractal dimension, etc.) for sets of cells with the same values
Analysis of remote sensing rasters
-
compositeRGB()
: Combine red, green, and blue color bands to make a compositeGRaster
-
plotRGB()
: Display a multispectralGRaster
using red, blue, green, and alpha channels -
vegIndex()
: Vegetation indices from surface reflectance
Functions that operate on terra SpatRaster
s
-
bioclims()
: BIOCLIM rasters (classic set and extended set) -
fragmentation()
: Landscape fragmentation class from Riitters et al. (2020)
Properties of GVector
s
-
crs()
: Coordinate reference system -
coordRef()
: Coordinate reference system -
datatype()
: Data type of fields -
dim()
: Number of geometries and columns -
expanse()
: Area of polygons or length of lines -
ext()
,N()
,S()
,E()
,W()
,top()
, andbottom()
: Spatial extent -
geomtype()
: Type of vector (points, lines, polygons) -
is.lonlat()
: Is an object projected (e.g., in WGS84)? -
is.points()
,is.lines()
,is.polygons()
: Does aGVector
represent points, lines, or polygons? -
names()
: Names ofGVector
fields -
ncol()
: Number of fields -
ngeom()
: Number of geometries (points, lines, polygons) -
nrow()
: Number of rows in a vector data table -
nsubgeom()
: Number of sub-geometries (points, lines, polygons that make up single- and multipart geometries) -
sources()
: Name of the vector file in the GRASS cache -
topology()
: Dimensionally (2D or 3D) -
zext()
: Vertical extent
Subsetting and assigning geometries or rows and columns of GVector
s
-
$<-
: Replace specific columns of aGVector
's data table or add columns -
addTable<-
: Add a data table to aGVector
-
dropTable()
: Remove aGVector
s data table
Operations on GVector
s
-
aggregate()
: CombineGVector
geometries -
as.data.frame()
: Convert aGVector
's attribute table to adata.frame
-
as.data.table()
: Convert aGVector
's attribute table to adata.table
-
as.points()
: Extract vertex coordinates from a "lines" or "polygons"GVector
-
buffer()
: Create a polygon around/inside aGVector
-
clusterPoints()
: Identify clusters of points -
centroids()
: Centroid(s) of aGVector
-
colbind()
: Add columns to the data table of aGVector
-
complete.cases()
: Find rows of aGVector
's data table that have noNA
s in them -
connectors()
: Create lines connecting nearest features of twoGVector
s -
convHull()
: Minimum convex hull -
crds()
: Extract coordinates of aGVector
-
crop()
: Remove parts of aGVector
-
delaunay()
: Delaunay triangulation -
disagg()
: Separate multipart geometries into singlepart geometries -
distance()
: Distance between geometries in twoGVector
, or from aGVector
to cells of aGRaster
-
erase()
or-
: Remove part of aGVector
that overlaps with another -
expanse()
: Area of polygons or length of lines -
extract()
: Extract values from aGVector
at specific points -
grid()
: Create a gridGVector
-
head()
: First rows of aGVector
's data table -
hexagons()
: Create a hexagonal grid -
interpIDW()
: Interpolate values at points to aGRaster
using inverse-distance weighting -
interpSplines()
: Interpolate values at points to aGRaster
using splines -
intersect()
or*
: Intersection of twoGVectors
-
kernel()
: Kernel density estimator of points -
missing.cases()
: Find rows of aGVector
's data table that have at leastNA
in them -
names<-
: Assign names to columns of aGVector
s data table -
neighborhoodMatrix()
andneighbourhoodMatrix()
: Neighborhood matrix of a polygonsGVector
-
project()
: Change coordinate reference system -
rasterize()
: Convert aGVector
to aGRaster
-
rbind()
: CombineGVectors
-
simplifyGeom()
: Remove vertices -
smoothGeom()
: Remove "angular" aspects of features -
st_as_sf()
: Convert aGVector
to asf
vector -
st_buffer()
: Create a polygon around/inside aGVector
-
tail()
: Last rows of aGVector
's data table -
thinPoints()
: Reduce number of points in same raster cell -
union()
or+
: Combine twoGVector
s -
voronoi()
: Voronoi tessellation -
xor()
or/
: Select parts of polygons not shared by twoGVector
s
Creating GVector
s de novo
-
rvoronoi()
: Random Voronoi tesselation
Fixing issues with GVector
s
(See also Details fast()
.)
-
breakPolys()
: Break topologically clean areas -
fillHoles()
: Fill "holes" of aGVector
-
fixBridges()
: Change "bridges" to "islands" -
fixDangles()
: Change "dangles" hanging off boundaries to lines -
fixLines()
: Break lines at intersections and lines that form closed loops -
remove0()
: Remove all boundaries and lines with a length of 0 -
removeAngles()
: Collapse lines that diverge at an angle that is computationally equivalent to 0 -
removeBridges()
: Remove "bridges" to "islands" -
removeDangles()
: Remove "dangling" lines -
removeDupCentroids()
: Remove duplicated area centroids -
removeDups()
: Remove duplicated features and area centroids -
removeSmallPolys()
: Remove small polygons -
snap()
: Snap lines/boundaries to each other
Converting between data types
-
as.contour()
: Convert aGRaster
to aGVector
representing contour lines -
as.doub()
: Convert aGRaster
to a double-floating point raster (GRASS data typeDCELL
) -
as.data.frame()
: ConvertGVector
to adata.frame
-
as.data.table()
: ConvertGVector
to adata.table
-
as.float()
: Convert aGRaster
to a floating-point raster (GRASS data typeFCELL
) -
as.int()
: Convert aGRaster
to an integer raster (GRASS data typeCELL
) -
as.points()
,as.lines()
, andas.polygons()
: Convert aGRaster
to aGVector
-
categories()
andlevels<-
: Convert an integer raster to a categorical ("factor") raster. -
fast()
: Convert aSpatRaster
to aGRaster
; aSpatVector
,sf
vector, numeric vector,matrix
,data.frame
, ordata.table
to aGVector
; or load a vector or raster from a file -
rast()
: Convert aGRaster
to aSpatRaster
-
rasterize()
: Convert aGVector
to aGRaster
-
st_as_sf()
: Convert aGVector
to asf
vector -
vect()
: Convert aGVector
to aSpatVector
General purpose functions
-
addons()
: Show installed GRASS addons -
compareGeom()
: Determine if geographic metadata is same betweenGRaster
s and/orGVector
s -
dropRows()
: Remove rows from adata.frame
ordata.table
-
grassGUI()
: Start the GRASS GUI (not recommended for most users!!!) -
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()
: ReplaceNA
s in columns of adata.table
ordata.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 aGRaster
orGVector
object
Data objects
-
fastData()
: Helper function to quickly obtain example rasters and vectors -
appFunsTable (see also
appFuns()
): Functions usable by theapp()
function -
madChelsa: Climate rasters for of a portion of eastern Madagascar
-
madCoast0, madCoast4, and madCoast: Borders of an eastern portion of Madagascar
-
madCover: Land cover raster
-
madCoverCats: Table of land cover classes
-
madDypsis: Specimens records of species in the genus Dypsis
-
madElev: Elevation raster
-
madForest2000 and madForest2014: Forest cover in 2000 and 2014
-
madLANDSAT: Surface reflectance in 2023
-
madPpt, madTmin, madTmax: Rasters of mean monthly precipitation, and minimum and maximum temperature
-
madRivers: Rivers vector
-
vegIndices: Vegetation indices that can be calculated using
vegIndex()
Esoteric tutorials and arcane notes
Comparisons between
GRegion
s can be performed using the==
and!=
operators.Vignette on GRASS "projects/locations" and "mapsets":
vignette("projects_mapsets", package = "fasterRaster")
Vignette on GRASS "regions":
vignette("regions", package = "fasterRaster")
Vignette on GRASS 3-dimensional
GRaster
s andGVector
s:vignette("three_d_objects", package = "fasterRaster")
Vignette on fasterRaster hidden functions:
vignette("hidden_functions", package = "fasterRaster")
Classes
-
GLocation
: Fundamental class; points to a "location/project" in GRASS -
GSpatial
: Basic class of any spatial object -
GRegion
: Points to a "region" of a "location/project" in GRASS -
GRaster
: Raster class -
GVector
: Spatial vector class
Author(s)
Adam B. Smith
See Also
Useful links:
Report bugs at https://github.com/adamlilith/fasterRaster/issues
Subset a GRaster layer, or return values from a column of a GVector's table
Description
The dollar
notation can be used to get a single layer of a multi-layer GRaster
or the values of a column from a GVector
's data table.
Usage
## S4 method for signature 'GRaster'
x$name
## S4 method for signature 'GVector'
x$name
Arguments
x |
A |
name |
Character: The name of a |
Value
A GRaster
or vector of the same type as the GVector
's column.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Replace a raster layer or a column from a vector's data table
Description
The $<-
notation can be used to replace a specific layer in a multi-layer GRaster
, or a to replace a specific column from a GVector
's data table.
Usage
## S4 replacement method for signature 'GRaster'
x$name <- value
## S4 replacement method for signature 'GVector'
x$name <- value
Arguments
x |
A |
name |
Character: Name of the |
value |
Character: The name of a |
Value
A GRaster
or the column of a GVector
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Setup fasterRaster for ABS
Description
This is a secret function to be used for faster development of fasterRaster. It calls faster()
to set the install directory for GRASS, increases default memory, and number of cores. The function assumes development is on a Windows machine.
Usage
.backdoor(ver = "84")
Arguments
ver |
Character: GRASS: e.g., "83" or "84". |
Value
TRUE
(invisibly).
Make a copy of an object in GRASS
Description
Create a copy of a GRaster
or GVector
in GRASS. This function is used internally and is of little use to most users. This only creates a copy of the object in the GRASS session–to make a GRaster
or GVector
, .makeGRaster()
or .makeGVector()
need to be called after making the copy. Note that if the object is multi-layered, then a copy is made of each layer.
Usage
## S4 method for signature 'GRaster'
.copyGSpatial(x, reshapeRegion = TRUE)
## S4 method for signature 'GVector'
.copyGSpatial(x)
## S4 method for signature 'character'
.copyGSpatial(x, type = NULL, topo = NULL, reshapeRegion = TRUE)
.copyGRaster(x, topo = "2D", reshapeRegion = TRUE)
.copyGVector(x)
Arguments
x |
A |
reshapeRegion |
Logical. If |
type |
Character or |
topo |
"2D" or "3D" |
Value
Character vector representing the sources()
names of the copied object(s), plus makes a copy of the given object(s) in GRASS.
sources()
names of copied rasters.
Does the "GRASS" representation of a GRaster or GVector exist?
Description
GRaster
s and GVector
s are R objects that contain a pointer to a raster or vector in GRASS. Thus, for a GRaster
or GVector
to be functional, the GRASS file must exist. This function indicates if that is so.
Usage
## S4 method for signature 'GRaster'
.exists(x)
## S4 method for signature 'GVector'
.exists(x)
## S4 method for signature 'character'
.exists(x)
Arguments
x |
A |
Value
Logical.
Function to get extent from a "sources" name of a raster or vector
Description
Function to get extent from a "sources" name of a raster or vector
Usage
.ext(x, rastOrVect = NULL)
Arguments
x |
A |
rastOrVect |
Either |
Value
A numeric vector.
Call GRASS g.proj
tool
Description
This function calls the GRASS tool g.region
to display information on the projection of the current GRASS "project".
Usage
.g.proj()
Value
Displays current projection information for the active "project/location" in GRASS.
Call GRASS g.region
tool
Description
This function calls the GRASS tool g.region
to display information on the region of the current GRASS "project".
Usage
.g.region()
Value
Displays current region information for the active "project/location" in GRASS.
Get geometry type from the sources() name of a vector
Description
Get geometry type from the sources() name of a vector
Usage
.geomtype(x)
Arguments
x |
A |
Value
Character ("point", "line", or "area"; i.e., in GRASS nomenclature).
Get index of raster layers
Description
Get index of raster layers
Usage
.layerIndex(layer, x, recycle = TRUE, negate = FALSE)
Arguments
layer |
Integer, numeric, logical, or character: Refers to one or more layers. |
x |
A |
recycle |
Logical: If |
negate |
Logical: If |
Value
An integer vector.
GRASS "location" of an object or the active session
Description
GRASS "projects" or "locations" are sets of one or more rasters and/or vectors with the same coordinate reference systems, and may or may not represent the same actual location on Earth. GRASS "mapsets" are like sub-folders of locations, and are collections of rasters and/or vectors typically related to the same general project. Typical users will not need to make changes to the default location (called "location") or mapset (called "PERMANENT"). See vignette("projects_mapsets", package = "fasterRaster")
.
This function deletes a GRASS "project"/"location", rasters, and vectors therein. This function should be used cautiously and is mainly of use to developers. See vignette("projects_mapsets", package = "fasterRaster")
.
Usage
## S4 method for signature 'GLocation'
.location(x)
## S4 method for signature 'missing'
.location(x)
.locationDelete(location, mapset = NULL, workDir = NULL)
Arguments
x |
Either:
|
location |
Character: Name of the GRASS "location". |
mapset |
Character or |
workDir |
Character: Either |
Value
A character string.
If successful, TRUE
(invisibly). If not, then FALSE
(also invisibly), plus a warning.
See Also
Connect to "GRASS"
Description
This function initializes a GRASS "project" (previously known in GRASS as a "location"; see vignette("projects_mapsets", package = "fasterRaster")
). You need to run this function (often just once) before you use most functions in fasterRaster. This function is of use to developers, not most users.
Usage
## S4 method for signature 'character'
.locationCreate(x, location = NULL, overwrite = FALSE, warn = TRUE)
## S4 method for signature 'SpatRaster'
.locationCreate(x, location = NULL, overwrite = FALSE, warn = TRUE)
## S4 method for signature 'SpatVector'
.locationCreate(x, location = NULL, overwrite = FALSE, warn = TRUE)
## S4 method for signature 'sf'
.locationCreate(x, location = NULL, overwrite = FALSE, warn = TRUE)
Arguments
x |
Any object from which a coordinate reference system (CRS) can be acquired. Ergo, any of:
|
location |
Character or |
overwrite |
Logical: If |
warn |
Logical: If |
Value
A GLocation object (invisibly).
Match CRS of a GSpatial object and an existing "GRASS" location
Description
The function searches the set of available GRASS "projects" (previously known as "locations") for one that has a coordinate reference system matching a GSpatial
object. If none are found, or if no connection with GRASS has yet been made, then it returns NULL
. Otherwise, it returns either the index or the name of the matching location.
Usage
## S4 method for signature 'missing'
.locationFind(x, return = "name")
## S4 method for signature 'GLocation'
.locationFind(x, return = "name", match = "name")
## S4 method for signature 'SpatRaster'
.locationFind(x, return = "name", match = "name")
## S4 method for signature 'SpatVector'
.locationFind(x, return = "name", match = "name")
## S4 method for signature 'sf'
.locationFind(x, return = "name", match = "name")
## S4 method for signature 'character'
.locationFind(x, return = "name", match = "name")
Arguments
x |
Either:
|
return |
Either:
|
match |
Character: Method used to find the location. If |
Value
Character, integer, or NULL
(if no match is found).
Revert to a previously-created "GRASS" "location"
Description
This function resets the connection to a previously-created GRASS "location". The session must have been already created using fast()
in the current R session. This function is typically only of use to developers.
Usage
## S4 method for signature 'character'
.locationRestore(x)
## S4 method for signature 'integer'
.locationRestore(x)
## S4 method for signature 'numeric'
.locationRestore(x)
## S4 method for signature 'GSpatial'
.locationRestore(x)
Arguments
x |
Either:
Any of these can be found using |
Value
An object of class GLocation
(invisibly) if successful. An error will likely result if not.
Meta-data on active GRASS locations
Description
GRASS uses "locations"to store sets of rasters and vectors with the same coordinate reference system (CRS). These rasters and vectors may or may not be in the same actual location on Earth–they just have the same CRS. This function returns information on all of the GRASS "locations" that have been initialized. It is mainly useful for developers.
NB: fasterRaster always uses the "PERMANENT" mapset.
Usage
.locations(warn = TRUE)
Arguments
warn |
Logical: If |
Value
A named list
. The names are the "location's" names and the values are the coordinate reference strings.
List objects in the active GRASS session
Description
Display the sources
(see sources()
) of all rasters and/or vectors that have been exported to or created in the active GRASS session"s location and mapset.
Usage
.ls(type = c("rasters", "vectors", "rasters3d", "groups"))
Arguments
type |
The type of spatial objects to display. This can include |
Value
Character vector of names of GRASS objects.
See Also
Create a GRaster
Description
Create a GRaster
from a raster existing in the current GRASS session.
Usage
.makeGRaster(src, names = "raster", levels = "", ac = NULL, fail = TRUE)
Arguments
src |
Character (name of the raster in **GRASS) or a |
names |
Character: Name of the raster. |
levels |
|
ac |
Vector of numeric/integer values >=1, or |
fail |
Logical: If |
Value
A GRaster
.
See Also
Create a GVector
Description
Create a GVector
from a vector existing in the current GRASS session.
Usage
.makeGVector(
src,
table = NULL,
build = TRUE,
extensive = FALSE,
cats = NULL,
fail = TRUE
)
Arguments
src |
Character: The name of the vector in GRASS. |
table |
A |
build |
Logical: If |
extensive |
Logical: If |
cats |
|
fail |
Logical: If |
Value
A GVector
(or NULL
if fail
is TRUE
and the GVector
would be invalid).
See Also
Make unique GRASS name for rasters, vectors, etc.
Description
Make unique GRASS name for rasters, vectors, etc.
Usage
.makeSourceName(x = NULL, type = NULL, n = 1L, name = NULL)
Arguments
x |
Character or |
type |
Character: |
n |
Numeric integer: Number of names to make |
name |
|
Value
Character vector.
GRASS "mapset" of an object or the active session
Description
GRASS "locations" are sets of one or more rasters and/or vectors with the same coordinate reference systems, and may or may not represent the same actual location on Earth. GRASS "mapsets" are like subfolders of locations, and are collections of rasters and/or vectors typically related to the same general project. This function returns the mapset of an object or the current mapset. This said, fasterRaster always uses the "PERMANENT" mapset, so there is very little reason to use this function as-is. See vignette("projects_mapsets", package = "fasterRaster")
.
Usage
## S4 method for signature 'GLocation'
.mapset(x)
## S4 method for signature 'missing'
.mapset(x)
Arguments
x |
A Either:
|
Value
A character string.
See Also
GRASS locations and mapsets
Get maximum value from GRaster metadata
Description
Get maximum value from GRaster metadata
Usage
.maxVal(x)
Arguments
x |
A |
Display warning or message
Description
Display a warning or message if the given warning has not been displayed since fasterRaster was attached or if a given number or hours has passed since then.
Usage
.message(msg, message)
Arguments
msg |
Character: Name for the message (used internally). Should be able to be assigned to a list (i.e., no spaces, punctuation, etc.). |
message |
Text for the message. |
Value
TRUE
(invisibly).
Get minimum value from GRaster metadata
Description
Get minimum value from GRaster metadata
Usage
.minVal(x)
Arguments
x |
A |
Count number of levels from a data.frame/table, list, or SpatRaster
Description
Counts number of levels in a character string (specifically, the empty string ""
), a data.frame
, data.table
, or list of data.frame
s or data.table
s or empty strings.
Usage
.nlevels(x)
Arguments
x |
A |
Plot using a G-object's sources()
name
Description
Plot using a G-object's sources()
name
Usage
.plot(x, ...)
Arguments
x |
The |
... |
Other arguments to pass to |
Get "GRASS" projection of raster or vector
Description
"Getter" for the @projection slot.
Usage
.projection(x)
Arguments
x |
A |
Value
Character.
Returns .quiet() or NULL for "flags" argument to GRASS modules
Description
A function for developers used for setting the "quiet' argument in flags
arguments passed to rgrass::execGRASS()
. If faster("debug")
is TRUE
, the string "quiet" is returned. If FALSE
, then NULL
is returned.
Usage
.quiet()
Value
A string (.quiet()) or NULL
.
Metadata on rasters and vectors in GRASS
Description
.rastInfo()
and .vectInfo()
fetch metadata on rasters and vectors in GRASS. The print()
, show()
, and summary()
functions can be used to display this metadata.
Usage
.rastInfo(x)
Arguments
x |
A |
Value
Metadata on the extent, dimensions, resolution, bottom/top, etc. of rasters and vectors in GRASS.
Report or change the extent, dimensions, and/or resolution of a region GRASS
Description
These functions either change the extent, dimensions, and/or resolution of a GRASS "region" or report the current region's extent, dimensions, and/or resolution (see vignette("regions", package = "fasterRaster")
). These functions are mostly used internally and rarely of interest to most users.
-
.region()
: All 2D and 3D aspects of a region. -
.regionDim()
: x- and y-dimensions. -
.regionExt()
: x- and y-extent. -
.regionRes()
: x- and y-resolution.
Usage
## S4 method for signature 'missing'
.region(x)
## S4 method for signature 'SpatRaster'
.region(x)
## S4 method for signature 'GRegion'
.region(x)
## S4 method for signature 'GRaster'
.region(x, trim = NULL)
## S4 method for signature 'GVector'
.region(x)
## S4 method for signature 'missing'
.regionExt(x)
## S4 method for signature 'numeric'
.regionExt(x, respect)
## S4 method for signature 'GSpatial'
.regionExt(x, respect)
## S4 method for signature 'missing'
.regionDim(x)
## S4 method for signature 'numeric'
.regionDim(x, respect)
## S4 method for signature 'GRegion'
.regionDim(x, respect)
## S4 method for signature 'missing'
.regionRes(x)
## S4 method for signature 'numeric'
.regionRes(x, respect)
## S4 method for signature 'GRegion'
.regionRes(x, respect)
Arguments
x |
Any of:
|
trim |
A |
respect |
Character or
In this case, the new region"s registration will be the same as this raster, and cell resolution will be the same Note: In most cases extent cannot be retained exactly if the resolution is changed. When resolution is changed, the actual extent will be the user-supplied extent expanded by zero to one rows or zero to one columns to accommodate an integer number of cells of the desired size. The western and northern limits of the extent will be retained, while the eastern and southern limits of the extent will be moved to accommodate an integer number of columns and rows. |
Details
When resizing extent, terra keeps the xmin
(west) and ymax
(north) the fixed and shifts xmax
(east) and ymin
(south) as needed. To retain as much fidelity between fasterRaster and terra as possible, these functions do the same to the region.
Value
The value returned depends on how the function is used:
If used with no arguments,
.region()
returns aGRegion
object.If used with no arguments,
.regionDim()
,.regionExt()
, and.regionRes()
return numeric or integer vectors.If the function is used to change reshape/resample the region, it returns a
GRegion
object reflecting the region before it was changed. This allows users to revert to the original region if desired.
Rename a raster or vector in an existing GRASS session
Description
Rename a raster or vector in an existing GRASS session.
Usage
.rename(from, to, rastOrVect = NULL)
Arguments
from , to |
|
rastOrVect |
Either |
Value
The function invisibly returns TRUE
if the desired rasters and/or vectors were named, and FALSE
if raster and/or vector to be renamed did not exist in the GRASS
session. Notably, a raster or vector or both are renamed in an existing GRASS
session.
Delete objects in the active GRASS session
Description
Delete the names of all rasters and/or vectors that have been exported to or created in the active GRASS session's location and mapset.
Usage
.rm(x, type = NULL, warn = TRUE, verify = TRUE)
Arguments
x |
Character, a
|
type |
The type of spatial objects to delete. This can include |
warn |
Logical: If |
verify |
Logical: If |
Value
TRUE
(invisibly).
See Also
Convert a GRASS vector's attribute table to a data.table
Description
GRASS vectors can be linked to an attribute table, which can be exported from GRASS to R using this function. This function is mostly of use to developers.
Values in the cat
column are not necessarily unique–if a value appears more than once, the set of features they index are (in other software) called "multipart" features. The table can have more columns with metadata for each feature.
This function is typically used by developers.
Usage
.vAsDataTable(x)
Arguments
x |
A |
Value
A data.table
or NULL
if the vector is not attached to a database.
Add a database table to a GRASS attribute table
Description
.vAttachDatabase()
adds a table to a GRASS vector. This table is meant to be "invisible" to most users–they should use interact with attribute tables using the GVector
slot @table
. Some functions require tables (e.g., extract()
and spatSample()
). This function is mostly of use to developers.
Usage
.vAttachDatabase(x, table = NULL, replace = TRUE, cats = NULL)
Arguments
x |
A |
table |
Either
There should be one row/value per geometry in |
replace |
Logical: If |
cats |
Either |
Value
Invisibly returns the sources()
name of a vector in GRASS.
Category column values of a GRASS vector
Description
Returns values in the cat
column of a vector in GRASS.
Usage
.vCats(x, layer = 1, db = FALSE, integer = TRUE)
Arguments
x |
A |
layer |
Integer, numeric integer, or character: Layer from which to obtain category values. |
db |
Logical: If |
integer |
Logical: If |
Value
A vector.
Add a database table to a GRASS attribute table
Description
.vDetachDatabase()
detaches the database from a GRASS vector and deletes it. This table is meant to be "invisible" to most users–they should use interact with attribute tables using the GVector
slot @table
. Some functions do require tables (e.g., extract()
and spatSample()
). This function is mostly of use to developers.
Usage
.vDetachDatabase(x)
Arguments
x |
A |
Value
Invisibly returns the sources()
name of a vector in GRASS.
Tests if a GRASS vector is linked to an attribute table
Description
GRASS vectors can be lined to one or more attribute tables, or "databases.". This function tests to see if the vector does indeed have a database. This function is typically used by developers.
Usage
.vHasDatabase(x)
Arguments
x |
A |
Value
Logical.
Increment category values of a "GRASS" vector
Description
Adds a constant to all category values of a GRASS vector. This function is mostly of use to developers.
Usage
.vIncrementCats(x, add)
Arguments
x |
A |
add |
Integer: Value to add to each category value. |
Value
The sources()
name of a GRASS vector with category values incremented.
Names of columns of a GRASS vector's attribute table
Description
This function returns the column names of a GRASS vector's attribute table.
Usage
.vNames(x)
Arguments
x |
A |
Value
Character vector.
Re-make vector "category" (cat) values
Description
Each geometry in a GRASS vector has a "category" number (abbreviated "cat" in output and modules). Geometries can have the same or different numbers, but for functions to work as intended, they often need to have sequential category values, starting at 1, with no skips between integers. This function reconstitutes the category values of a vector in GRASS so they being with 1 and have no skips. This function is mostly of use to developers.
Usage
.vRecat(x, gtype, cats = NULL)
Arguments
x |
A |
gtype |
Character: Type of vector features in GRASS format (i.e., either |
cats |
|
Value
The sources()
name of a vector.
See Also
Are the category values of a vector valid?
Description
Category values of a GRASS vector can be invalid if GRASS assigns more than one value to a geometry (e.g., "7/12"). This can occur when the vector was created by software that does not use a topological system (e.g., a shapefile).
Usage
.vValidCats(x)
Arguments
x |
A |
Value
Logical.
Metadata on a vector in GRASS
Description
This function queries GRASS to obtain metadata on a vector.
Usage
.vectInfo(x, integer = TRUE, cats = NULL)
Arguments
x |
A |
integer |
Logical. If |
cats |
|
Value
A vectInfo
object (a list).
Get a GLocation's working directory
Description
This function returns the working directory of a GLocation
object.
Usage
## S4 method for signature 'GLocation'
.workDir(x)
## S4 method for signature 'missing'
.workDir(x)
Arguments
x |
A |
Value
Character.
Internal function for zonal()
Description
Internal function for zonal()
Usage
.zonal(x, z, fun, probs, zones, xnames)
Arguments
x |
|
z |
|
fun |
Character: Name of function(s). |
probs |
Numeric in the range 0 to 1, inclusive. |
zones |
Vector of zone values (integers). |
xnames |
Character: Names of |
Internal function for zonal() when y is a GVector
Description
Internal function for zonal() when y is a GVector
Usage
.zonalByVector(x, z, fun, probs, gtype)
Arguments
x |
GRaster |
z |
GVector |
fun |
Character |
gtype |
|
Arithmetic operations on GRasters
Description
GRaster
s: You can do arithmetic operations on GRaster
s and using normal operators in R: +
, -
, *
, /
, ^
, %%
(modulus), and %/%
(integer division).
GVector
s: You can also do arithmetic operations on GVector
s:
+
operator: Same as union()
-
operator: Same as erase()
*
operator: Same as intersect()
/
operator: Same as xor()
Usage
## S4 method for signature 'GRaster,logical'
Arith(e1, e2)
## S4 method for signature 'logical,GRaster'
Arith(e1, e2)
## S4 method for signature 'GRaster,numeric'
Arith(e1, e2)
## S4 method for signature 'GRaster,integer'
Arith(e1, e2)
## S4 method for signature 'numeric,GRaster'
Arith(e1, e2)
## S4 method for signature 'integer,GRaster'
Arith(e1, e2)
## S4 method for signature 'GRaster,GRaster'
Arith(e1, e2)
## S4 method for signature 'GVector,GVector'
Arith(e1, e2)
Arguments
e1 , e2 |
|
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
elevs <- c(elev, elev, log10(elev) - 1, sqrt(elev))
names(elevs) <- c("elev1", "elev2", "log_elev", "sqrt_elev")
elev
elevs
# do some math
elev + 100
elev - 100
elev * 100
elev / 100
elev ^ 2
elev %/% 100 # divide then round down
elev %% 100 # modulus
100 + elev
100 %/% elev
100 %% elev
elevs + 100
100 + elevs
# math with logicals
elev + TRUE
elev - TRUE
elev * TRUE
elev / TRUE
elev ^ TRUE
elev %/% TRUE # divide then round down
elev %% TRUE # modulus
elevs + TRUE
TRUE + elevs
# Raster interacting with raster(s):
elev + elev
elev - elev
elev * elev
elev / elev
elev ^ log(elev)
elev %/% sqrt(elev) # divide then round down
elev %% sqrt(elev) # modulus
elevs + elev
elev * elevs
# sign
abs(-1 * elev)
abs(elevs)
# powers
sqrt(elevs)
# trigonometry
sin(elev)
cos(elev)
tan(elev)
asin(elev)
acos(elev)
atan(elev)
atan(elevs)
atan2(elev, elev^1.2)
atan2(elevs, elev^1.2)
atan2(elev, elevs^1.2)
atan2(elevs, elevs^1.2)
# logarithms
exp(elev)
log(elev)
ln(elev)
log2(elev)
log1p(elev)
log10(elev)
log10p(elev)
log(elev, 3)
log(elevs)
# rounding
round(elev + 0.5)
floor(elev + 0.5)
ceiling(elev + 0.5)
trunc(elev + 0.5)
}
Compare-methods operations on GRasters and GRegions
Description
You can do comparative operations on GRaster
s using normal operators in R: <
, <=
, ==
, !=
, >=
, and >
. You can also use %in%
for categorical GRasters
(see vignette("GRasters", package = "fasterRaster")
).
You can also compare two GRegion
s using the ==
and !=
operators. Most users of fasterRaster will not have to work much with "regions" (see vignette("regions", package = "fasterRaster")
), so can ignore this functionality. GRegion
s are the same if they have the same coordinate reference system, location/project and mapset (see vignette("projects_mapsets", package = "fasterRaster")
), topology (2D or 3D), extent, and resolution. If both are 3D, then they must also have the same vertical extent and number of depths.
Usage
## S4 method for signature 'GRaster,GRaster'
Compare(e1, e2)
## S4 method for signature 'logical,GRaster'
Compare(e1, e2)
## S4 method for signature 'GRaster,logical'
Compare(e1, e2)
## S4 method for signature 'numeric,GRaster'
Compare(e1, e2)
## S4 method for signature 'GRaster,numeric'
Compare(e1, e2)
## S4 method for signature 'GRaster,integer'
Compare(e1, e2)
## S4 method for signature 'integer,GRaster'
Compare(e1, e2)
## S4 method for signature 'GRaster,character'
Compare(e1, e2)
## S4 method for signature 'character,GRaster'
Compare(e1, e2)
## S4 method for signature 'GRegion,GRegion'
Compare(e1, e2)
Arguments
e1 , e2 |
Values depend on the type of comparison:
|
Value
Comparing GRaster
s: An "integer" GRaster
with values of 0 (FALSE), 1 (TRUE), or NA
(neither).
Comparing GRegion
s: Output is logical.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
elevs <- c(elev, elev, log10(elev) - 1, sqrt(elev))
names(elevs) <- c("elev1", "elev2", "log_elev", "sqrt_elev")
elev
elevs
# Comparisons
elev < 100
elev <= 100
elev == 100
elev != 100
elev > 100
elev >= 100
elev + 100 < 2 * elev
elevs > 10
10 > elevs
# logic
elev < 10 | elev > 200
elev < 10 | cos(elev) > 0.9
elev < 10 | TRUE
TRUE | elev > 200
elev < 10 | FALSE
FALSE | elev > 200
elev < 10 & cos(elev) > 0.9
elev < 10 & TRUE
TRUE & elev > 200
elev < 10 & FALSE
FALSE & elev > 200
}
Classes for fasterRaster sessions, regions, rasters, and vectors
Description
The G
-suite of S4 classes contain pointers to GRASS objects or metadata about the current GRASS session. Most users will manipulate objects using these classes, but do not need to know the details.
The
GLocation
class stores information about the GRASS "project"/"location"(seevignette("projects_mapsets", package = "fasterRaster")
), and coordinate reference system. Contained by all the rest.The
GSpatial
class contains theGLocation
class and stores information about spatial objects (extent, topology) plus the name of the file representing it in GRASS (itssource
). Contained byGRegion
,GRaster
, andGVector
.The
GRegion
class contains theGSpatial
class and stores information about grids (dimensions and resolution). They do havesources
, but these are not used (they're alwaysNA
). Contained byGRaster
. TheGRegion
corresponds to GRASS "regions", thoughGRegion
objects are not actually pointers to GRASS "region" files (seevignette("regions", package = "fasterRaster")
).The
GRaster
class contains theGRegion
class and represents rasters. It stores information on number of layers, categories, min/max values, and user-friendly names. CategoricalGRaster
s are associated with a "levels" table for representing categorical data (e.g., wetlands, forest, etc.).The
GVector
class contains theGSpatial
class and represents spatial vectors. It may or may not have an associateddata.table
(i.e., adata.frame
), which contains metadata about each geometry in the vector.
Value
An object of class GLocation
, GSpatial
, GRegion
, GRaster
, or GVector
.
Slots
location
Character (all classes): The GRASS "project"/"location" of the object. The default value is
default
. Can be obtained using the hidden function.location()
. Seevignette("projects_mapsets", package = "fasterRaster")
.mapset
Character (all classes): The GRASS "mapset". Default value is
PERMANENT
. Typically hidden to users. Can be obtained using the hidden function.mapset()
. Seevignette("projects_mapsets", package = "fasterRaster")
.workDir
Character (all classes): Directory in which GRASS stores files.
topology
Character (
GSpatial
objects, includingGRegion
s,GRaster
s, andGVector
s): Valid values are2D
(2-dimensional–most rasters and vectors) or3D
(3-dimensional–e.g., LIDAR data). Can be obtained usingtopology()
.sources
Character (
GRaster
s andGVector
s): Name of the object in GRASS. These are typically made on-the-fly and provide the pointer to the object from R to GRASS. Changing them manually will break the connection. Can be obtained usingsources()
.names
Character (
GRaster
s only): Name of a raster or each raster layer in. Can be obtained usingnames()
.crs
Character (all classes): Coordinate reference systems string (preferably in WKT2 format). Can be obtained using
crs()
orst_crs()
.projection
Character: The GRASS "projection" for a
GRaster
orGVector
. Can be obtained using.projection()
.dimensions
Dimensions:
-
GRegion
s andGRaster
s: Vector of three integers indicating number of rows, columns, and depths (for 3D objects). Can be obtained usingdim()
, plusnrow()
,ncol()
, andndepth()
. -
GVectors
s: Vector of two integers indicating number of geometries and number of fields. Can be obtained usingdim()
, plusnrow()
andncol()
.
-
extent
Numeric vector with four values (
GSpatial
objects, includingGRegion
s,GRaster
s, andGVector
s): Extent of the object listed in order from westernmost longitude, easternmost longitude, southernmost latitude, northernmost latitude. Can be obtained usingext()
.zextent
Numeric (
GSpatial
objects, includingGRegion
s,GRaster
s, andGVector
s): Bottom- and top-most extents of 3DGRaster
s andGVector
s. Can be obtained usingzext()
.geometry
Character (
GVectors
s): Eitherpoints
,lines
, orpolygons
. Can be obtained usinggeomtype()
.nLayers
Integer (
GRaster
s): Number of layers ("stacked" rasters–different from number of depths of 3D rasters). Can be obtained usingnlyr()
.nGeometries
Integer (
GVector
s): Number of features (points, lines, or polygons). Can be obtained usingnrow()
.datatypeGRASS
Character (
GRaster
s): Type of data stored in a raster, as interpreted byGRASS
. This is eitherCELL
(integers),FCELL
(floating-point values), orDCELL
(double-values). Can be obtained usingdatatype()
.resolution
Vector of two numeric values (
GRegion
s, includingGRaster
s): Size of a raster cell in the east-west direction and in the north-south direction. Can be obtained usingres()
andres3d()
.minVal,maxVal
Numeric (
GRaster
s): Minimum and maximum value across all cells. Can be obtained usingminmax()
.activeCat
Integer (
GRaster
s): Column index of the category labels. Must be >0. Note that from the user's standpoint, 1 is subtracted from this number. So a value if@activeCat
is2
, then the user would see "1" when printed. Can be obtained usingactiveCat()
.levels
List of
data.table
s (GRaster
s): Tables for categorical rasters. If a raster is not categorical, thedata.table
isNULL
, as indata.table(NULL)
. Can be obtained usinglevels()
orcats()
.table
data.table
(GVector
s): Table with metadata, one row per geometry (point, line, or plane). If no table is associated with the vector, this must bedata.table(NULL)
. The column with the category value is given in@catName
.catName
Character (
GVector
s): Name of the column in the vector's database that contains category values (integers).
Logic-methods operations on GRasters
Description
You can do logical operations on GRaster
s. A cell with a value of 1 is interpreted as TRUE
, and a value of 0 is interpreted as FALSE
. You can compare:
A
GRaster
to anotherGRaster
A
GRaster
to a logical value (TRUE
orFALSE
, but notNA
–seenot.na()
)A
GRaster
to a numeric or integer value that is 0 or 1
Operators include:
-
|
:TRUE
if either condition isTRUE
(or 1), but returnsNA
if either condition isNA
. -
&
:TRUE
if both conditions areTRUE
(or 1), butNA
if either isNA
.
Usage
## S4 method for signature 'GRaster,GRaster'
Logic(e1, e2)
## S4 method for signature 'logical,GRaster'
Logic(e1, e2)
## S4 method for signature 'GRaster,logical'
Logic(e1, e2)
## S4 method for signature 'GRaster,numeric'
Logic(e1, e2)
## S4 method for signature 'numeric,GRaster'
Logic(e1, e2)
## S4 method for signature 'GRaster,integer'
Logic(e1, e2)
## S4 method for signature 'integer,GRaster'
Logic(e1, e2)
Arguments
e1 , e2 |
Two |
Value
A binary GRaster
(1 ==> TRUE
, 0 ==> FALSE
, plus NA
when comparison results in NA
).
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
elevs <- c(elev, elev, log10(elev) - 1, sqrt(elev))
names(elevs) <- c("elev1", "elev2", "log_elev", "sqrt_elev")
elev
elevs
# Comparisons
elev < 100
elev <= 100
elev == 100
elev != 100
elev > 100
elev >= 100
elev + 100 < 2 * elev
elevs > 10
10 > elevs
# logic
elev < 10 | elev > 200
elev < 10 | cos(elev) > 0.9
elev < 10 | TRUE
TRUE | elev > 200
elev < 10 | FALSE
FALSE | elev > 200
elev < 10 & cos(elev) > 0.9
elev < 10 & TRUE
TRUE & elev > 200
elev < 10 & FALSE
FALSE & elev > 200
}
Subset geometries of a GVector
Description
The [
operator returns a subset or remove specific geometries of a GVector
. You can get the number of geometries using ngeom()
. Note that you cannot use this function to change the "order" in which geometries or their associated records in a data table appear. For example, vector[1:3]
and vector[3:1]
will yield the exact same results.
Note that subsetting can take a very long time if you are retaining only a small number of geometries from a vector with many geometries. The routine selects geometries by removing those that are not in i
. So if you can write code to remove fewer geometries (i.e., an "inverse" selection), it may go faster.
Usage
## S4 method for signature 'GVector,ANY,ANY'
x[i, j]
## S4 method for signature 'GRaster,GRaster,ANY'
x[i, j]
Arguments
x |
A |
i |
Numeric integer, integer, or logical vector: Indicates which geometry(ies) to obtain. Negative numeric or integer values will remove the given geometries from the output. If a logical vector is supplied and it is not the same length as the number of geometries, it will be recycled. |
j |
Numeric integer, integer, logical, or character: Indices or name(s) of the column(s) to obtain. You can see column names using |
Value
A GVector
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Replace values of a GRaster
Description
The [<-
operator can be used to replace all of the values of a GRaster
, or specific values depending on the expression in i
. For example, you could use rast[] <- 10
to assign 10 to all cells, or rast[rast > 0] <- 10
to assign all cells with values >0 to 10. You can also use one raster to set values in another, as in rast1[rast2 > 0] <- 10
.
Usage
## S4 replacement method for signature 'GRaster,missing,ANY'
x[i, j] <- value
## S4 replacement method for signature 'GRaster,GRaster,ANY'
x[i, j] <- value
Arguments
x |
A |
i |
Either missing or a conditional statement that resolves to a |
j |
Not used |
value |
A numeric, integer, or logical value, or |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Subset layers from a GRaster, or specific columns from a GVector
Description
The [[
operator can be used to subset or remove one or more layers from a GRaster
. It can also be used to subset or remove columns from a GVector
with a data table.
Usage
## S4 method for signature 'GRaster,ANY,ANY'
x[[i, j]]
## S4 method for signature 'GVector,ANY,ANY'
x[[i, j]]
Arguments
x |
A |
i |
Numeric integer, integer, logical, or character: Indicates the layer(s) of a |
j |
Ignored for |
Value
A GRaster
or GVector
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Replace layers of a GRaster
Description
The [[<-
operator can be used to replace a layer in a multi-layer GRaster
.
Usage
## S4 replacement method for signature 'GRaster,ANY'
x[[i]] <- value
Arguments
x |
A |
i |
A numeric integer, integer, logical, or character: Indicates the layer to replace. If a logical vector, then the vector must have the same length as there are layers in |
value |
Either a |
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Get or set the column with category labels in a categorical raster
Description
These functions return or set the column of the labels to be matched to each value in the raster of a categorical GRaster
(see vignette("GRasters", package = "fasterRaster")
). Important: Following terra::activeCat()
, the first column in the "levels" table is ignored, so an "active category" value of 1 means the second column is used as labels, a value of 2 means the third is used, and so on.
-
activeCat()
returns the column of the labels to be matched to each value in the raster for a single raster layer. -
activeCats()
does the same, but for all layers of aGRaster
. -
activeCat()<-
sets the column to be used as category labels.
Usage
## S4 method for signature 'GRaster'
activeCat(x, layer = 1, names = FALSE)
## S4 method for signature 'GRaster'
activeCats(x, names = FALSE)
## S4 replacement method for signature 'GRaster'
activeCat(x, layer = 1) <- value
## S4 replacement method for signature 'GRaster'
activeCat(x, layer = 1) <- value
## S4 replacement method for signature 'GRaster'
activeCat(x, layer = 1) <- value
Arguments
x |
A categorical |
layer |
Numeric, integer, logical, or character: Indicates for which layer(s) to get or set the active category column. This can be a number (the index of the raster(s)), a logical vector ( |
names |
Logical: If |
value |
Numeric, integer, or character. Following |
Value
activeCat()
returns an integer or character of the active column index or name. activeCats()
returns a vector of indices or names. activeCat()<-
returns a GRaster
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
"Stack" a GRaster
Description
This function "stacks" one GRaster
with another. It has the same functionality as c()
.
Usage
## S4 replacement method for signature 'GRaster,GRaster'
add(x) <- value
Arguments
x , value |
A |
Value
A GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Add rows or columns to the "levels" table of a categorical raster
Description
addCats()
and addCats()<-
add information to a categorical‘GRaster’s "levels" table.
addCats()' uses
data.table::merge()
orcbind()
to do this–it does not add new rows, but rather new columns.-
addCats()<-
usesrbind()
to add new categories (rows) to the "levels" table.
GRasters can represent categorical data (see
vignette("GRasters", package = "fasterRaster")). Cell values are actually integers, each corresponding to a category, such as "desert" or "wetland." A categorical raster is associated with a "levels" table that matches each value to a category name. The table must be
NULL' (i.e., no categories–so not a categorical raster), or have at least two columns. The first column must have integers and represent raster values. One or more subsequent columns must have category labels. The column with these labels is the "active category".
Usage
## S4 method for signature 'GRaster'
addCats(x, value, merge = FALSE, layer = 1)
## S4 replacement method for signature 'GRaster'
addCats(x, layer = 1) <- value
Arguments
x |
A |
value |
A |
merge |
Logical (function |
layer |
Numeric integers, logical vector, or character: Layer(s) to which to add or from which to drop levels. |
Value
A GRaster
. The "levels" table of the raster is modified.
See Also
terra::addCats()
, concats()
, combineLevels()
, droplevels()
, vignette("GRasters", package = "fasterRaster"
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Attach or detach GVector's data table
Description
addTable()
adds an entire table to a GVector
. It will replace any existing table. There must be one row in the table for each geometry (see ngeom()
). You can also add a table column-by-column using the $<-
operator.
dropTable()
removes a data table associated with a GVector
.
Usage
## S4 replacement method for signature 'GVector,data.frame'
addTable(x, ...) <- value
## S4 replacement method for signature 'GVector,data.table'
addTable(x, ...) <- value
## S4 replacement method for signature 'GVector,matrix'
addTable(x, ...) <- value
## S4 method for signature 'GVector'
dropTable(x)
Arguments
x |
A |
... |
Other arguments (ignored). |
value |
A |
Value
A GVector
.
See Also
$<-
, colbind()
, rbind()
, as.data.frame()
, as.data.table()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Rivers vector
madRivers <- fastData("madRivers")
# Convert sf to a GVector
rivers <- fast(madRivers)
# Convert GVector to data.frame or data.table
as.data.frame(rivers)
as.data.table(rivers)
# Subset rivers vector
rivers1 <- rivers[1:2]
rivers2 <- rivers[10:11]
# Concatenate rivers
riversCombo <- rbind(rivers1, rivers2)
riversCombo
# Add columns
newCol <- data.frame(new = 1:11)
riversCol <- colbind(rivers, newCol)
riversCol
# Remove table
riversCopy <- rivers
riversCopy # has data table
riversCopy <- dropTable(riversCopy)
riversCopy # no data table
# Add a new table
newTable <- data.frame(num = 1:11, letters = letters[1:11])
addTable(riversCopy) <- newTable
riversCopy
}
Test if addons directory exists and if an addon is installed
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.
-
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.
Usage
addons(x = NULL)
installAddon(x, check = TRUE)
removeAddon(x, check = TRUE)
.addons(x)
Arguments
x |
Either |
check |
Logical: If |
Value
addons()
: Logical. The other functions invisibly return a logical value indicating if the operation succeeded or not.
Examples
if (grassStarted()) {
# What addons are installed?
addons()
# Is a specific addon installed?
addons(c("v.centerpoint", "fake.addon"))
}
Aggregate raster cells into larger cells or combine geometries of a vector
Description
When applied to a GRaster
, aggregate()
creates a new raster with cells that are a multiple of the size of the cells of the original raster. The new cells can be larger or smaller than the original cells (this function thus emulates both the terra::aggregate()
and terra::disagg()
functions.)
When applied to a GVector
, all geometries are combined into a "multipart" geometry, in which geometries are treated as if they were a single unit. Borders between aggregated geometries can be dissolved if the dissolve
argument is TRUE
. If the GVector
has a data table associated with it, the output will also have a data table as long as there is at least one column with values that are all the same. Values of columns that do not have duplicated values will be converted to NA
.
Usage
## S4 method for signature 'GRaster'
aggregate(
x,
fact = 2,
fun = "mean",
weight = FALSE,
prob = NULL,
na.rm = FALSE
)
## S4 method for signature 'GVector'
aggregate(x)
Arguments
x |
A |
fact |
Numeric vector (rasters only): One, two, or three positive values. These reflect the size of the new cells as multiples of the size of the old cells. If just one value is supplied, this is used for all two or three dimensions. If two values are supplied, the first is multiplied by the east-west size of cells, and the second north-south size of cells (the raster must be 2D). If three values are supplied, the third value is used as the multiplier of the vertical dimension of cells. Values are calculated using all cells that have their centers contained by the target cell. Note that unlike |
fun |
Character (rasters only): Name of the function used to aggregate. For
|
weight |
Logical (rasters only): If |
prob |
Numeric (rasters only): Quantile at which to calculate |
na.rm |
Logical (rasters only): If |
Value
A GRaster
or GVector
.
See Also
stats::aggregate()
, terra::aggregate()
, disagg()
, terra::disagg()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madCoast4 <- fastData("madCoast4")
### aggregating a GRaster
# Convert:
elev <- fast(madElev)
### Aggregate GRaster by same factor in 2 dimensions
# fasterRaster
agg2 <- aggregate(elev, 2, "mean")
agg2
# Compare rasters aggregated by fasterRaster and terra.
# These should be the same.
agg2terra <- aggregate(madElev, 2)
agg2 <- rast(agg2)
agg2 <- extend(agg2, agg2terra)
agg2 - agg2terra # value is ~0
### Aggregate GRaster by a non-integer factor in 2 dimensions
# fasterRaster
agg2.9 <- aggregate(elev, 2.9, "mean")
agg2.9
# terra
agg2.9terra <- aggregate(madElev, 2.9, "mean")
agg2.9terra
# Compare rasters aggregated by fasterRaster and terra.
# These should be different.
res(agg2.9)
res(agg2.9terra) # terra rounds aggregation factor down
2 * res(madElev) # original resolution multiplied by 2
### Aggregate GRaster by different factor in 2 dimensions
agg2x3 <- aggregate(elev, c(2, 3), "mean")
agg2x3
### aggregating a GVector
madCoast4 <- fastData("madCoast4")
# Convert:
coast4 <- fast(madCoast4)
# Aggregate and disaggregate:
aggCoast <- aggregate(coast4)
disaggCoast <- disagg(coast4)
ngeom(coast4)
ngeom(aggCoast)
ngeom(disaggCoast)
# plot
oldpar <- par(mfrow = c(1, 3))
plot(coast4, main = "Original", col = 1:nrow(coast4))
plot(aggCoast, main = "Aggregated", col = 1:nrow(aggCoast))
plot(disaggCoast, main = "Disaggregated", col = 1:nrow(disaggCoast))
par(oldpar)
}
Apply a function to a set of rasters
Description
app()
applies a function to a set of "stacked" rasters. It is similar to the terra::app()
and terra::lapp()
functions.
appFuns()
provides a table of GRASS functions that can be used by app()
and their equivalents in R.
appCheck()
tests whether a formula supplied to app()
has any "forbidden" function calls.
The app()
function operates in a manner somewhat different from terra::app()
. The function to be applied must be written as a character string. For example, if the GRaster
had layer names "x1
" and "x2
", then the function might be like "= max(sqrt(x1), log(x2))"
. Rasters cannot have the same names as functions used in the formula. In this example, the rasters could not be named "max", "sqrt", or "log". Note that the name of a GRaster
is given by names()
–this can be different from the name of the object in R.
The app()
function will automatically check for GRaster
names that appear also to be functions that appear in the formula. However, you can check a formula before running app()
by using the appCheck()
function. You can obtain a list of app()
functions using appFuns()
. Note that these are sometimes different from how they are applied in R.
Tips:
Make sure your
GRaster
s havenames()
. The function matches on these, not the name of the variable you use in R for theGRaster
.Use
null()
instead ofNA
, and useisnull()
instead ofis.na()
.If you want to calculate values using while ignoring
NA
(ornull
) values, see the functions that begin withn
(likenmean
).Be mindful of the data type that a function returns. In GRASS, these are
CELL
(integer),FCELL
(floating point values–precise to about the 7th decimal place), andDCELL
(double-floating point values–precise to about the 15th decimal place; commensurate with the Rnumeric
type). In cases where you want aGRaster
to be treated like a float or double type raster, wrap the name of theGRaster
in thefloat()
ordouble()
functions. This is especially useful if theGRaster
might be assumed to be theCELL
type because it only contains integer values. You can get the data type of a raster usingdatatype()
with thetype
argument set toGRASS
. You can change the data type of aGRaster
usingas.int()
,as.float()
, andas.doub()
. Note that categorical rasters are reallyCELL
(integer) rasters with an associated "levels" table. You can also change aCELL
raster to aFCELL
raster by adding then subtracting a decimal value, as inx - 0.1 + 0.1
. Seevignette("GRasters", package = "fasterRaster")
.The
rand()
function returns integer values by default. If you want non-integer values, use the tricks mentioned above to datatype non-integer values. For example, if you want uniform random values in the range between 0 and 1, use something like= float(rand(0 + 0.1, 1 + 0.1) - 0.1)
.
Usage
## S4 method for signature 'GRaster'
app(x, fun, datatype = "auto", seed = NULL)
appFuns(warn = TRUE)
## S4 method for signature 'GRaster,character'
appCheck(x, fun, msgOnGood = TRUE, failOnBad = TRUE)
Arguments
x |
A |
fun |
Character: The function to apply. This must be written as a character string that follows these rules:
The help page for GRASS tool |
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:
|
seed |
Numeric integer vector or |
warn |
Logical (function |
msgOnGood |
Logical (function |
failOnBad |
Logical (function |
Value
A GRaster
.
See Also
terra::app()
, terra::lapp()
, subst()
, classify()
, and especially the GRASS manual page for tool r.mapcalc
(see grassHelp("r.mapcalc")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert SpatRaster to a GRaster:
elev <- fast(madElev)
# Create a "stack" of rasters for us to operate on:
x <- c(elev, elev^2, sqrt(elev))
# Demonstrate check for badly-named rasters:
names(x) <- c("cos", "asin", "exp")
fun <- "= cos / asin + exp"
appCheck(x, fun, failOnBad = FALSE)
# Rename rasters acceptable names and run the function:
names(x) <- c("x1", "x2", "x3")
fun <- "= (x1 / x2) + x3"
appCheck(x, fun, failOnBad = FALSE)
app(x, fun = fun)
# This is the same as:
(x[[1]] / x[[2]]) + x[[3]]
# We can view a table of app() functions using appFuns():
appFuns()
# We can also get the same table using:
data(appFunsTable)
# Apply other functions:
fun <- "= median(x1 / x2, x3, x1 * 2, cos(x2))"
app(x, fun = fun)
fun <- "= round(x1) * tan(x2) + log(x3, 10)"
app(x, fun = fun)
# Demonstrate effects of data type:
fun <- "= x1 + x3"
app(x, fun = fun, datatype = "float") # output is floating-point
app(x, fun = fun, datatype = "integer") # output is integer
# Some functions override the "datatype" argument:
fun <- "= sin(x2)"
app(x, fun = fun, datatype = "integer")
# Make a raster with random values [1:4], with equal probability of each:
fun <- "= round(rand(0.5, 4.5))"
rand <- app(elev, fun = fun)
rand
freqs <- freq(rand) # cell frequencies
print(freqs)
}
Functions that can be used in app()
Description
This is a table of functions that can be used in the app()
function, their R equivalents, and the datatype()
they return. You can view this table using ?appFunsTable
or as a searchable, sortable Shiny table using appFuns()
.
Format
A data.frame
.
Source
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert SpatRaster to a GRaster:
elev <- fast(madElev)
# Create a "stack" of rasters for us to operate on:
x <- c(elev, elev^2, sqrt(elev))
# Demonstrate check for badly-named rasters:
names(x) <- c("cos", "asin", "exp")
fun <- "= cos / asin + exp"
appCheck(x, fun, failOnBad = FALSE)
# Rename rasters acceptable names and run the function:
names(x) <- c("x1", "x2", "x3")
fun <- "= (x1 / x2) + x3"
appCheck(x, fun, failOnBad = FALSE)
app(x, fun = fun)
# This is the same as:
(x[[1]] / x[[2]]) + x[[3]]
# We can view a table of app() functions using appFuns():
appFuns()
# We can also get the same table using:
data(appFunsTable)
# Apply other functions:
fun <- "= median(x1 / x2, x3, x1 * 2, cos(x2))"
app(x, fun = fun)
fun <- "= round(x1) * tan(x2) + log(x3, 10)"
app(x, fun = fun)
# Demonstrate effects of data type:
fun <- "= x1 + x3"
app(x, fun = fun, datatype = "float") # output is floating-point
app(x, fun = fun, datatype = "integer") # output is integer
# Some functions override the "datatype" argument:
fun <- "= sin(x2)"
app(x, fun = fun, datatype = "integer")
# Make a raster with random values [1:4], with equal probability of each:
fun <- "= round(rand(0.5, 4.5))"
rand <- app(elev, fun = fun)
rand
freqs <- freq(rand) # cell frequencies
print(freqs)
}
Contour lines from a "GRaster"
Description
Create a GVector
of contour lines from a GRaster
.
Usage
## S4 method for signature 'GRaster'
as.contour(x, nlevels, levels)
Arguments
x |
A |
nlevels |
Numeric: A positive integer or missing (default). Number of levels at which to calculate contours. Levels will be calculated in equal-sized steps from the smallest to the largest value of |
levels |
Numeric vector: A numeric vector of values at which to calculate contour lines. Either |
Value
A GVector
representing contour lines.
See Also
terra::as.contour()
, GRASS manual page for tool r.contour
(see grassHelp("r.contour")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Calculate contour lines:
conts <- as.contour(elev, nlevels = 10)
plot(elev)
plot(conts, add = TRUE)
}
Convert GVector to a data frame
Description
Convert a GVector
's data table to a data.frame
or data.table
.
Usage
## S4 method for signature 'GVector'
as.data.frame(x)
## S4 method for signature 'GVector'
as.data.table(x)
Arguments
x |
A |
Value
A data.frame
or NULL
(if the GRaster
has no data table).
See Also
terra::as.data.frame()
, data.table::as.data.table()
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Coerce raster to integer, float, or double precision
Description
In fasterRaster, rasters can have three data types: "factor" (categorical rasters), "integer" (integers), "float" (floating point values, accurate to 6th to 9th decimal places), and "double" (double-precision values, accurate to the 15th to 17th decimal places). The type of raster can be checked with:
-
as.int()
: Coerce values to integers (GRASS typeCELL
). -
as.float()
: Coerce values to floating-point precision. -
as.doub()
: Coerce values to double-floating point precision. Integer rasters can be converted categorical rasters by adding "levels" tables with
levels<-
orcategories()
.
Usage
## S4 method for signature 'GRaster'
as.int(x)
## S4 method for signature 'GRaster'
as.float(x)
## S4 method for signature 'GRaster'
as.doub(x)
Arguments
x |
A |
Value
A GRaster
.
See Also
datatype()
, terra::datatype()
, is.int()
, is.float()
, is.doub()
, levels<-
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Convert a raster to a lines vector
Description
as.lines()
converts a GRaster
to a "lines" GVector
. Before you apply this function, you may need to run thinLines()
on the raster to reduce linear features to a single-cell width. You may also need to use clean geometry (especially the removeDups()
and removeDangles()
) afterward to remove duplicated vertices and "dangling" lines.
Usage
## S4 method for signature 'GRaster'
as.lines(x)
Arguments
x |
A |
Value
A GVector
.
See Also
as.points()
, as.polygons()
, terra::as.lines()
, thinLines()
, geometry cleaning, and GRASS tool r.to.vect
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation
madElev <- fastData("madElev")
# Convert to GRaster:
elev <- fast(madElev)
# Thin elevation raster:
thinned <- thinLines(elev, iter = 300)
plot(thinned)
# Convert to lines:
rastToLines <- as.lines(thinned)
plot(rastToLines)
# We can clean this:
cleanLines <- fixDangles(x = rastToLines)
plot(rastToLines, col = "red")
plot(cleanLines, add = TRUE)
}
Convert a GRaster, or lines or polygons GVector to a points vector
Description
as.points()
converts a GRaster
, or a lines or polygons GVector
to a points GVector
.
For GRasters
, the points have the coordinates of cell centers and are assigned the cells' values. Only non-NA
cells will be converted to points.
For GVectors
, each point will have the attributes of the line or polygon to which it belonged. Points are extracted from each vertex.
Usage
## S4 method for signature 'GRaster'
as.points(x, values = TRUE)
## S4 method for signature 'GVector'
as.points(x)
Arguments
x |
A |
values |
Logical: If |
Value
A points
GVector
.
See Also
crds()
, as.lines()
, as.polygons()
, terra::as.points()
, and modules v.to.points
and r.to.vect
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster, outline of a part of Madagascar, and rivers vector:
madElev <- fastData("madElev")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
# Convert to GRaster and GVectors:
elev <- fast(madElev)
coast <- fast(madCoast0)
rivers <- fast(madRivers)
# For this example, we will first crop to a small extent.
river <- rivers[1]
elevCrop <- crop(elev, river)
elevPoints <- as.points(elevCrop)
elevPoints
plot(elevCrop)
plot(elevPoints, pch = '.', add = TRUE)
# Extract points from vectors:
coastPoints <- as.points(coast)
riversPoints <- as.points(rivers)
plot(coast)
plot(coastPoints, add = TRUE)
plot(rivers, col = "blue", add = TRUE)
plot(riversPoints, col = "blue", add = TRUE)
}
Convert a raster to a polygons vector
Description
as.polygons()
converts a GRaster
to a "polygons" GVector
. After running this function, geometry cleaning may be useful to use to "tidy up" the vector.
Usage
## S4 method for signature 'GRaster'
as.polygons(x, round = TRUE, smooth = FALSE)
Arguments
x |
A |
round |
Logical: If |
smooth |
Logical: If |
Value
A GVector
.
See Also
as.points()
, as.lines()
, terra::as.polygons()
, geometry cleaning, and GRASS tool r.to.vect
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation
madElev <- fastData("madElev")
# Convert SpatRaster to GRaster:
elev <- fast(madElev)
# To speed things up, first group cells of similar value:
elevClumps <- clump(elev, minDiff = 0.0115)
# Convert to polygons:
rastToPolys <- as.polygons(elevClumps)
plot(rastToPolys)
}
BIOCLIM rasters
Description
The BIOCLIM set of bioclimatic variables were created for modeling species' geographic distributions (Booth et al. 2014). This function can create the "standard" 19 set of variables, plus several more from an "extended" set.
"Classic" set of BIOCLIM variables (Booth et al. 2014): The units reported below assume that input rasters are in mm (precipitation) and deg C (temperature), and that each raster represents a month (but other time units are allowed, with corresponding changes to the temporal units assumed below).
BIO1: Mean annual temperature, calculated using monthly means (deg C)
BIO2: Mean diurnal range across months (average of monthly difference between maximum and minimum temperature) (deg C)
BIO3: Isothermality (100 * BIO02 / BIO07; unit-less)
BIO4: Temperature seasonality (standard deviation across months of average monthly temperature * 100; deg C)
BIO5: Maximum temperature of the warmest month (based on maximum temperature; deg C)
BIO6: Minimum temperature of the coldest month (based on minimum temperature; deg C)
BIO7: Range of annual temperature (BIO05 - BIO06; deg C)
BIO8: Temperature of the wettest quarter (based on mean temperature; deg C)
BIO9: Temperature of the driest quarter (based on mean temperature; deg C)
BIO10: Temperature of the warmest quarter (based on mean temperature; deg C)
BIO11: Temperature of the coldest quarter (based on mean temperature; deg C)
BIO12: Total annual precipitation (mm)
BIO13: Precipitation of the wettest month (mm)
BIO14: Precipitation of the driest month (mm)
BIO15: Precipitation seasonality (100 * coefficient of variation; unit-less)
BIO16: Precipitation of the wettest quarter (mm)
BIO17: Precipitation of the driest quarter (mm)
BIO18: Precipitation of the warmest quarter (based on mean temperature; mm)
BIO19: Precipitation of the coldest quarter (based on mean temperature; mm)
"Extended" set of BIOCLIM variables (starts at 41 to avoid conflicts with Kriticos et al. 2014):
BIO41: Temperature of the quarter following the coldest quarter (based on mean temperature; deg C)
BIO42: Temperature of the quarter following the warmest quarter (based on mean temperature; deg C)
BIO43: Precipitation of the quarter following the coldest quarter (based on mean temperature; mm)
BIO44: Precipitation of the quarter following the warmest quarter (based on mean temperature; mm)
BIO45: Temperature of the quarter following the driest quarter (based on mean temperature; deg C)
BIO46: Temperature of the quarter following the wettest quarter (based on mean temperature; deg C)
BIO47: Precipitation of the quarter following the driest quarter (based on mean temperature; mm)
BIO48: Precipitation of the quarter following the wettest quarter (based on mean temperature; mm)
BIO49: Hottest month (based on maximum temperature)
BIO50: Coldest month (based on minimum temperature)
BIO51: Wettest month
BIO52: Driest month
BIO53: First month of the warmest quarter (based on mean temperature)
BIO54: First month of the coldest quarter (based on mean temperature)
BIO55: First month of the wettest quarter
BIO56: First month of the driest quarter
BIO57: The greatest decrease in temperature from one month to the next (deg C; always >= 0)
BIO58: The greatest increase in temperature from one month to the next (deg C; always >= 0)
BIO59: The greatest decrease in precipitation from one month to the next (mm; always >= 0)
BIO60: The greatest increase in precipitation from one month to the next (mm; always >= 0)
By default, "quarter" refers to any consecutive run of three months, not a financial quarter. A quarter can thus include November-December-January, or December-January-February, for example. However, the length of a quarter can be changed using the argument quarter
.
The variables are defined assuming that the input rasters represent monthly values (12 rasters for min/max temperature and precipitation), but you can also use sets of 52 rasters, representing one per week, in which case "quarter" would be a successive run of 3 weeks. You could also attempt 365 rasters, in which case a "quarter" would be a run of 3 successive days.
BIOCLIMs 41 through 44 are added here to capture the "shoulder" seasons (spring and autumn) important in temperature regions. BIOCLIMs 45 through 48 are also included for consistency.
BIOCLIMs 49 through 60 are not bioclimatic variables per se, but useful for assessing the properties of the variables that are defined based on the "-est" month or quarter.
Usage
## S4 method for signature 'GRaster'
bioclims(
ppt,
tmin,
tmax,
tmean = NULL,
bios = NULL,
sample = TRUE,
quarter = 3,
pptDelta = 1,
verbose = TRUE
)
## S4 method for signature 'SpatRaster'
bioclims(
ppt,
tmin,
tmax,
tmean = NULL,
bios = NULL,
sample = TRUE,
quarter = 3,
pptDelta = 1,
verbose = TRUE
)
Arguments
ppt |
A multi-layered |
tmin , tmax |
A multi-layered |
tmean |
Either |
bios |
Any of:
|
sample |
Logical: If |
quarter |
Numeric: Length of a "quarter". BIOCLIM variables are typically calculated using monthly-averaged rasters (e.g., precipitation and temperature of January, February, etc.), in which case a "quarter" is 3 months (so the default for |
pptDelta |
Numeric: Value to add to precipitation for calculation of BIO15 (coefficient of variation of precipitation, times 100). Adding a small value avoids division by 0. The default is 1. |
verbose |
Logical: If |
Value
A GRaster
with one or more layers.
References
Booth, T.H., Nix, H.A., Busby, J.R., and Hutchinson, M.F. 2014. BIOCLIM: The first species distribution modeling package, its early applications and relevance to most current MaxEnt studies. Diversity and Distributions 20:1-9 doi:10.1111/ddi.12144.
Kriticos, D.J., Jarošik, V., and Otam N. 2014. Extending the suite of BIOCLIM variables: A proposed registry system and case study using principal components analysis. Methods in Ecology and Evolution 5:956-960 doi:10.1111/2041-210X.12244.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Load rasters with precipitation and min/max temperature
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
### Classic and extended BIOCLIMs from SpatRasters
bcSR <- bioclims(madPpt, madTmin, madTmax, bios = "*")
bcSR
### BIOCLIMs from GRasters
ppt <- fast(madPpt)
tmin <- fast(madTmin)
tmax <- fast(madTmax)
# For small rasters, takes longer to run compared to SpatRaster version:
bc <- bioclims(ppt, tmin, tmax, bios = c(1, 5, 12))
bc
plot(bc)
}
Fix issues with geometries of a vector
Description
These functions are intended to help fix geometric issues with a GVector
. Note that the functionality of the snap()
and removeAreas()
functions can also be implemented when using fast()
to create a GVector
.
-
breakPolys()
: Break topologically clean areas. This is similar tofixLines()
, except that it does not break loops. Topologically clean vectors may occur if the vector was imported from a format that does not enforce topology, such as a shapefile. Duplicate geometries are automatically removed after breaking. -
fixBridges()
: Change "bridges" to "islands" (which are topologically incorrect) within geometries to lines. -
fixDangles()
: Change "dangles" hanging off boundaries to lines if shorter thantolerance
distance. Iftolerance
is <0, all dangles will be changed to lines. Units oftolerance
are in map units, or in degrees for unprojected CRSs. Iftolerance
<0, all dangles are removed, and the function will retain only closed loops and lines connecting loops. Dangles will be removed from longest to shortest. -
fixLines()
: Break lines at intersections and lines that form closed loops. -
remove0()
: Remove all boundaries and lines with a length of 0. -
removeAngles()
: Collapse lines that diverge at an angle that is computationally equivalent to 0. This tool often needs to be followed with thebreak()
andremoveDups()
methods. -
removeBridges()
: Remove "bridges" to "islands" (which are topologically incorrect) within geometries. -
removeDangles()
: Remove "dangling" lines if shorter thantolerance
distance. Iftolerance
is <0, all dangles will be removed. Units oftolerance
are in map units, or in degrees for unprojected CRSs. Iftolerance
<0, all dangles are removed, and the function will retain only closed loops and lines connecting loops. Dangles will be removed from longest to shortest. -
removeDupCentroids()
: Remove duplicated area centroids. In GRASS, closed polygons have their attributes mapped to a (hidden) centroid of the polygon. -
removeDups()
: Remove duplicated features and area centroids. -
removeSmallPolys()
: Remove polygons smaller thantolerance
. Units oftolerance
are in square meters (regardless of the CRS). -
snap()
: Snap lines/boundaries to each other if they are less thantolerance
apart. Subsequent removal of dangles may be needed. Units oftolerance
are map units, or degrees for unprojected CRSs.
Usage
## S4 method for signature 'GVector'
breakPolys(x)
## S4 method for signature 'GVector'
fixBridges(x)
## S4 method for signature 'GVector'
fixDangles(x, tolerance = -1)
## S4 method for signature 'GVector'
fixLines(x)
## S4 method for signature 'GVector'
remove0(x)
## S4 method for signature 'GVector'
removeAngles(x)
## S4 method for signature 'GVector'
removeBridges(x)
## S4 method for signature 'GVector'
removeDangles(x, tolerance = -1)
## S4 method for signature 'GVector'
removeDupCentroids(x)
## S4 method for signature 'GVector'
removeDups(x)
## S4 method for signature 'GVector'
removeSmallPolys(x, tolerance)
## S4 method for signature 'GVector'
snap(x, tolerance)
Arguments
x |
A |
tolerance |
Numeric or |
Value
A GVector
.
See Also
terra::topology()
, fillHoles()
, terra::removeDupNodes()
, Details section in fast()
, simplifyGeom()
, smoothGeom()
, GRASS manual page for tool v.clean
(see grassHelp("v.clean")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madRivers <- fastData("madRivers")
rivers <- fast(madRivers)
soam <- rivers[rivers$NAM == "SOAMIANINA"] # select one river for illustration
### Simplify geometry (remove nodes)
vr <- simplifyGeom(soam, tolerance = 2000)
dp <- simplifyGeom(soam, tolerance = 2000, method = "dp")
dpr <- simplifyGeom(soam, tolerance = 2000, method = "dpr", prop = 0.5)
rw <- simplifyGeom(soam, tolerance = 2000, method = "rw")
plot(soam, col = "black", lwd = 3)
plot(vr, col = "blue", add = TRUE)
plot(dp, col = "red", add = TRUE)
plot(dpr, col = "chartreuse", add = TRUE)
plot(rw, col = "orange", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Vertex reduction",
"Douglas-Peucker",
"Douglas-Peucker reduction",
"Reumann-Witkam"
),
col = c("black", "blue", "red", "chartreuse", "orange"),
lwd = c(3, 1, 1, 1, 1)
)
### Smooth geometry
hermite <- smoothGeom(soam, dist = 2000, angle = 3)
chaiken <- smoothGeom(soam, method = "Chaiken", dist = 2000)
plot(soam, col = "black", lwd = 2)
plot(hermite, col = "blue", add = TRUE)
plot(chaiken, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Hermite",
"Chaiken"
),
col = c("black", "blue", "red"),
lwd = c(2, 1, 1, 1, 1)
)
### Clean geometry
# Has no effect on this vector!
noDangs <- removeDangles(soam, tolerance = 10000)
plot(soam, col = "black", lwd = 2)
plot(noDangs, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"No dangles"
),
lwd = c(2, 1),
col = c("black", "red")
)
}
Increase/decrease the size of a vector or around non-NA cells of a raster
Description
Buffers can be constructed for GRaster
s or GVector
s. For rasters, the buffer()
function creates a buffer around non-NA
cells. The output will be a raster. For vectors, the buffer()
and st_buffer()
functions create a vector polygon larger or smaller than the focal vector.
Usage
## S4 method for signature 'GRaster'
buffer(
x,
width,
unit = "meters",
method = "Euclidean",
background = 0,
lowMemory = FALSE
)
## S4 method for signature 'GVector'
buffer(x, width, capstyle = "round", dissolve = TRUE)
## S4 method for signature 'GVector'
st_buffer(x, dist, endCapStyle = "round", dissolve = FALSE)
Arguments
x |
A |
width |
Numeric: For rasters – Maximum distance cells must be from focal cells to be within the buffer. For rasters, if the buffering unit is For vectors, distance from the object to place the buffer. Negative values create "inside" buffers. Units are in the same units as the current coordinate reference system (e.g., degrees for WGS84 or NAD83, often meters for projected systems). |
unit |
Character: Rasters – Indicates the units of
Partial matching is used and case is ignored. |
method |
Character: Rasters – Only used if
Partial matching is used and case is ignored. |
background |
Numeric: Rasters – Value to assign to cells that are not |
lowMemory |
Logical: Rasters – Only used if buffering a raster and |
capstyle , endCapStyle |
Character: Vectors – Style for ending the "cap" of buffers around lines. Valid options include |
dissolve |
Logical ( |
dist |
Vectors – Same as |
Details
Note that in some cases, topologically incorrect vectors can be created when buffering. This can arise when buffers intersect to create intersections that technically belong to two or more geometries. This issue can be resolved by dissolving borders between buffered geometries using dissolve = TRUE
, but as of now, there is no fix if you do not want to dissolve geometries. A workaround would be to create a different GVector
for each geometry, and then buffer each individually :(.
Value
A GRaster
or a GVector
.
See Also
terra::buffer()
, sf::st_buffer()
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster, rivers vector
madElev <- fastData("madElev")
madRivers <- fastData("madRivers")
# Convert a SpatRaster to a GRaster, and sf to a GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
### Buffer a raster by a given distance:
buffByDist <- buffer(elev, width = 2000) # 2000-m buffer
plot(buffByDist, legend = FALSE)
plot(madElev, add = TRUE)
### Buffer a raster by a given number of cells:
buffByCells <- buffer(elev, width = 20.01, unit = "cells") # 20-cell buffer
plot(buffByCells, legend = FALSE)
plot(madElev, add = TRUE)
### Buffer a vector:
buffRivers <- buffer(rivers, width = 2000, dissolve = TRUE) # 2000-m buffer
plot(buffRivers)
plot(st_geometry(madRivers), col = "blue", add = TRUE)
}
"Stack" GRasters
Description
GRaster
s can be "stacked" using this function, effectively creating a multi-layered raster. This is different from creating a 3-dimensional raster, though such an effect can be emulated using stacking. GVector
s can be combined into a single vector. Stacks can only be created when:
All objects are the same class (either all
GRaster
s or allGVector
s).All objects have the same coordinate reference system (see crs()).
Horizontal extents are the same (see
ext()
).Horizontal dimensions are the same (see
res()
).The topology (2- or 3-dimensional) must be the same. If 3D, then all rasters must have the same number of depths and vertical extents (see
topology()
).
Data tables associated with GVector
s will be combined if each vector has a table and if each table has the same columns and data types. Otherwise, the data table will be combined using merge()
.
Usage
## S4 method for signature 'GRaster'
c(x, ...)
Arguments
x |
A |
... |
One or more |
Value
A GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
madForest2000 <- fastData("madForest2000")
madForest2014 <- fastData("madForest2014")
# Convert SpatRasters to GRasters:
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Combine:
forest <- c(forest2000, forest2014)
forest
nlyr(forest)
}
Names of columns of the levels table of a categorical raster
Description
This function returns the column names of each "levels" table of a categorical raster (see vignette("GRasters", package = "fasterRaster")
).
Usage
## S4 method for signature 'GRaster'
catNames(x, layer = NULL)
## S4 method for signature 'SpatRaster'
catNames(x, layer = NULL)
Arguments
x |
A |
layer |
|
Value
A list of character vectors.
See Also
cats()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Area of GRaster cells
Description
cellArea()
returns a raster will cell values equal to their area. To get the area of all cells of a raster, see expanse()
.
Usage
## S4 method for signature 'GRaster'
cellSize(x, mask = FALSE, lyrs = FALSE, unit = "meters2")
Arguments
x |
A |
mask |
Logical: If |
lyrs |
Logical:
|
unit |
Character: Units of area. Partial matching is used, and case is ignored. Can be any of:
|
Value
A GRaster
.
See Also
terra::cellSize()
, expanse()
, zonalGeog()
, omnibus::convertUnits()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Cell size, no masking, single layer
cs1 <- cellSize(elev)
plot(cs1)
# Cell size, with masking, single layer
cs2 <- cellSize(elev, mask = TRUE)
plot(cs2)
# Cell size, no masking, multilayer
elev2 <- c(elev, log(elev - 200))
cs3 <- cellSize(elev2)
plot(cs3)
# Cell size, masking by 1st layer, multilayer (ignores subsequent layers)
cs4 <- cellSize(elev2, mask = TRUE)
plot(cs4)
# Cell size, masking by each layer, multilayer
cs5 <- cellSize(elev2, mask = TRUE, lyrs = TRUE)
plot(cs5)
}
Centroid(s) of a vector or clumps in a raster
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 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.
Usage
## S4 method for signature 'GVector'
centroids(x, method = NULL)
## S4 method for signature 'GRaster'
centroids(x)
Arguments
x |
A |
method |
Partial matching is used and case is ignored. |
Value
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.
See Also
terra::centroids()
; GRASS addon tools v.centerpoint
and r.centroids
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
### Points, line, and polygon centroids
# Point centroids:
madDypsis <- fastData("madDypsis")
dypsis <- fast(madDypsis)
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 = "blue", pch = 3, add = TRUE)
legend("bottomright",
legend = c("mean", "median", "pmedian"),
col = c("red", "green", "blue"),
pch = c(16, 2, 3),
xpd = NA
)
# Line centroids:
madRivers <- fastData("madRivers")
rivers <- fast(madRivers)
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 = "blue", pch = 3, add = TRUE)
legend("bottomright",
legend = c("mid", "mean", "median"),
col = c("red", "green", "blue"),
pch = c(16, 2, 3),
xpd = NA
)
# Polygon centroids:
madCoast4 <- fastData("madCoast4")
coast4 <- fast(madCoast4)
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 = "blue", pch = 3, add = TRUE)
legend("bottomright",
legend = c("mean", "median", "bmedian"),
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)
}
Classify GRaster cell values
Description
This function classifies a 'GRaster“ so that cells that have values within a given range are assigned a new value. The subst()
function is a simpler method for replacing specific values or category levels.
Usage
## S4 method for signature 'GRaster'
classify(x, rcl, include.lowest = FALSE, right = TRUE, others = NULL)
Arguments
x |
A |
rcl |
Reclassification system:
|
include.lowest , right |
Logical: These arguments determine how cells that have values exactly equal to the lower or upper ends of an interval are classified.
|
others |
Integer or |
Value
A GRaster
. The raster will be a categorical GRaster
if the original values were continuous (i.e., a single- or double-precision raster), or of type "integer" if the input was an integer. See vignette("GRasters", package = "fasterRaster")
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Classify using a scalar indicating number of bins
scalar <- classify(elev, 5)
scalar
levels(scalar)
# Classify using a vector, indicating bin break points
vector <- classify(elev, rcl = c(0, 100, 200, 300, 400, 500, 600))
vector
levels(vector)
# Classify using a 2-column matrix (only valid for integer rasters)
rcl <- data.frame(is = c(1:3, 5, 10), becomes = c(100:102, 105, 110))
twoCol <- classify(elev, rcl = rcl)
twoCol
# Classify using a 3-column table
rcl <- data.frame(
from = c(0, 100, 200, 300, 400, 500),
to = c(100, 200, 300, 400, 500, 600),
becomes = c(1, 2, 3, 10, 12, 15)
)
threeCol <- classify(elev, rcl = rcl)
threeCol
levels(threeCol)
# Convert all values outside range to NA (default)
rcl <- c(100, 200, 300)
v1 <- classify(elev, rcl = rcl)
v1
plot(v1)
# Convert all values outside range to -1
rcl <- c(100, 200, 300)
v2 <- classify(elev, rcl = rcl, others = -1)
v2
plot(v2)
### Left-open/right-closed (default)
minmax(elev) # note min/max values
rcl <- c(1, 200, 570)
v3 <- classify(elev, rcl = rcl, others = 10)
levels(v3)
plot(v3)
### Left-closed/right-open
minmax(elev) # note min/max values
rcl <- c(1, 200, 570)
v4 <- classify(elev, rcl = rcl, others = 10, right = FALSE)
levels(v4)
# Left-open except for lowest bin/right-closed
minmax(elev) # note min/max values
rcl <- c(1, 200, 570)
v5 <- classify(elev, rcl = rcl, others = 10, include.lowest = TRUE)
v5 <- droplevels(v5)
levels(v5)
# Left-closed/right-open except for highest bin
minmax(elev) # note min/max values
rcl <- c(1, 200, 570)
v6 <- classify(elev, rcl = rcl, others = 10,
right = FALSE, include.lowest = TRUE)
v6 <- droplevels(v6)
levels(v6)
}
Group adjacent cells with similar values
Description
clump()
identifies groups of adjacent cells that have the same value or same approximate value, and assigns them a unique number, creating "clumps" of same- or similar-valued cells.
Usage
## S4 method for signature 'GRaster'
clump(x, minDiff = 0, minClumpSize = 1, diagonal = TRUE)
Arguments
x |
A |
minDiff |
Numeric in the range [0, 1): Minimum difference between cells in order for them to be assigned to the same clump. This is a proportion of the range across all cells. For example, if |
minClumpSize |
Numeric integer >= 1. Minimum number of cells in a clump. The default is 1. |
diagonal |
Logical: If |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Find clumps based on exact values. This will appear as a gradient because
# most cells are assigned to a group of 1 cell.
exact <- clump(elev)
plot(exact)
# Clump based on approximate values:
approx <- clump(elev, minDiff = 0.0075)
plot(approx)
# Clump based on approximate values with minimum clump size:
approx20 <- clump(elev, minDiff = 0.005, minClumpSize = 20)
plot(approx20)
approx
approx20
}
Identify clusters of points
Description
clusterPoints()
partitions points in a "points" GVector
into clusters.
Usage
## S4 method for signature 'GVector'
clusterPoints(x, method = "DBSCAN", minIn = NULL, maxDist = NULL)
Arguments
x |
A "points" |
method |
Character: Method used to identify clusters. Explanations of methods are provided in the help page for the GRASS tool
Case is ignored, but partial matching is not used. |
minIn |
Integer, numeric integer, or |
maxDist |
Numeric or |
Value
A vector of integers indicating the cluster to which each point belongs.
See Also
GRASS manual page for tool v.cluster
(see grassHelp("v.cluster")
)
Add columns to the data table of a GVector
Description
colbind()
adds columns to the data table of a GVector
. You can combine multiple a GVector
's data table with data.frame
s, data.table
s, matrices
, or the data table(s) from other GVector
(s). To combine two GVector
s, see rbind()
.
Usage
## S4 method for signature 'GVector'
colbind(x, ...)
Arguments
x , ... |
The first argument must be a |
Value
A GVector
.
See Also
rbind()
, addTable<-
, dropTable()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Rivers vector
madRivers <- fastData("madRivers")
# Convert sf to a GVector
rivers <- fast(madRivers)
# Convert GVector to data.frame or data.table
as.data.frame(rivers)
as.data.table(rivers)
# Subset rivers vector
rivers1 <- rivers[1:2]
rivers2 <- rivers[10:11]
# Concatenate rivers
riversCombo <- rbind(rivers1, rivers2)
riversCombo
# Add columns
newCol <- data.frame(new = 1:11)
riversCol <- colbind(rivers, newCol)
riversCol
# Remove table
riversCopy <- rivers
riversCopy # has data table
riversCopy <- dropTable(riversCopy)
riversCopy # no data table
# Add a new table
newTable <- data.frame(num = 1:11, letters = letters[1:11])
addTable(riversCopy) <- newTable
riversCopy
}
Combine levels table from multiple categorical GRasters
Description
This function creates a single "levels" table from the levels tables of one or more categorical GRaster
s.
The difference between this function and concats()
is that concats()
creates a "combined" GRaster
with a combined levels table, whereas this one just merges the levels tables.
Usage
## S4 method for signature 'GRaster'
combineLevels(x, ...)
## S4 method for signature 'list'
combineLevels(x, ...)
Arguments
x |
A |
... |
Arguments to pass to |
Value
A list
with a "levels" table (a data.frame
or data.table
), and the active category number for the new table. Following terra::activeCat()
, the number is offset by 1, so a value of 1 indicates that the second column in the table should be used for the category labels, a value of 2 indicates the third column should be used, and so on.
See Also
concats()
, terra::concats, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Determine if GRasters and/or GVectors are geographically comparable
Description
compareGeom()
compares geographic metadata between two or more GRaster
s and/or GVector
s. In many cases, spatial objects must be comparable for them to "interact" (e.g., conducting arithmetic operations, masking, etc.).
Usage
## S4 method for signature 'GRaster,GRaster'
compareGeom(
x,
y,
...,
location = TRUE,
mapset = TRUE,
topo = TRUE,
lyrs = FALSE,
crs = TRUE,
ext = TRUE,
zext = TRUE,
rowcol = TRUE,
depths = TRUE,
res = TRUE,
zres = TRUE,
stopOnError = TRUE,
messages = TRUE
)
## S4 method for signature 'GVector,GVector'
compareGeom(
x,
y,
...,
location = TRUE,
mapset = TRUE,
topo = FALSE,
crs = TRUE,
ext = FALSE,
zext = FALSE,
geometry = FALSE,
stopOnError = TRUE,
messages = TRUE
)
## S4 method for signature 'GRaster,GVector'
compareGeom(
x,
y,
...,
location = TRUE,
mapset = TRUE,
topo = FALSE,
crs = TRUE,
ext = FALSE,
zext = FALSE,
stopOnError = TRUE,
messages = TRUE
)
## S4 method for signature 'GVector,GRaster'
compareGeom(
x,
y,
...,
location = TRUE,
mapset = TRUE,
topo = FALSE,
crs = TRUE,
ext = FALSE,
zext = FALSE,
stopOnError = TRUE,
messages = TRUE
)
Arguments
x , y , ... |
|
location , mapset |
Logical: Compare GRASS "project/location" and "mapsets" (see |
topo |
Logical: Test for same topology (2D or 3D). By default, this is |
lyrs |
Logical (rasters only): Compare number of layers of "stacked" rasters. Note this is different from number of vertical "depths" of a raster. Default is |
crs |
Logical: Compare coordinate reference systems. Default is |
ext |
Logical: If |
zext |
Logical: Test for same vertical extents (3D only). By default, this is |
rowcol |
Logical (rasters only): Test for same number of rows and columns. Default is |
depths |
Logical (rasters only): Test for same number of depths. Default is |
res |
Logical (rasters only): Test for same resolution in x- and y-dimensions. Default is |
zres |
Logical (rasters only): Test for same resolution in z dimension. Default is |
stopOnError |
Logical: If |
messages |
Logical: If |
geometry |
Logical (vector-vector comparison only): Compare geometry. Default is |
Value
Logical (invisibly): TRUE
for no mismatches detected, FALSE
for incompatibility), or side effect of throwing an error.
Rows of a GRaster or GVector's table that have no NAs or that have NAs
Description
When applied to a categorical GRaster
, compete.cases()
returns TRUE
for each row of the "levels" table that has no NA
s in it. In contrast, missing.cases()
returns TRUE
for each row that has at least one NA
in it. If the raster is not categorical, then NA
is returned.
When applied to a GVector
with a data table, complete.cases()
returns TRUE
for each row where there are no NA
s. if the GVector
has no data table, then a vector of TRUE
values the same length as the total number of geometries will be returned. In contrast, missing.cases()
returns TRUE
for every row that has at least one NA
in it. If the GVector
has no data table, then a vector of FALSE
values is returned.
Usage
## S4 method for signature 'GRaster'
complete.cases(..., levels = TRUE)
## S4 method for signature 'GVector'
complete.cases(...)
## S4 method for signature 'GRaster'
missing.cases(..., levels = TRUE)
## S4 method for signature 'GVector'
missing.cases(...)
Arguments
... |
A |
levels |
Logical ( |
Value
Both complete.cases()
and missing.cases()
return the same type of object. The output depends on the input:
A categorical
GRaster
with just one layer: A logical vector.An integer, float, or double
GRaster
with just one layer:NA
.A
GRaster
with multiple layers: A list with one element per layer with either logical vectors orNA
s, as per above.A
GVector
with a data table: A logical vector.A
GVector
without a data table:NA
.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Plant specimens (points) and land cover
madDypsis <- fastData("madDypsis")
madCover <- fastData("madCover")
# Convert to GVector and GRaster
dypsis <- fast(madDypsis)
cover <- fast(madCover)
### GVector
# Look at the data table:
as.data.table(dypsis)
# Which rows have no NAs?
complete.cases(dypsis)
# Which rows have at least one NA (opposite of above)?
missing.cases(dypsis)
### GRaster
# Look at the levels table:
levels(cover)
# Which rows of levels table have no NAs?
complete.cases(cover)
# Which rows have at least one NA (opposite of above)?
missing.cases(cover)
}
Combine red, green, and blue color bands to make a composite GRaster
Description
This function takes as arguments three rasters typically representing red, green, and blue color bands, and returns a single raster with values based on their combination. Typically, this raster should be plotted in grayscale.
Usage
## S4 method for signature 'GRaster'
compositeRGB(r, g = NULL, b = NULL, levels = 256, dither = FALSE)
Arguments
r , g , b |
Either:
|
levels |
Either a single value that is an integer, or a vector of integers: Number of levels of red, green, and blue intensities represented in |
dither |
Logical: If |
Value
A GRaster
.
See Also
plotRGB()
, terra::plotRGB()
, GRASS manual page for tool r.composite
(see grassHelp("r.composite")
)
Examples
if (grassStarted()) {
# Example data
madElev <- fastData("madElev") # elevation raster
madLANDSAT <- fastData("madLANDSAT") # multi-layer raster
madRivers <- fastData("madRivers") # lines vector
# Convert SpatRaster to GRaster and SpatVector to GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
landsat <- fast(madLANDSAT)
# Plot:
plot(elev)
plot(rivers, add = TRUE)
# Histograms:
hist(elev)
hist(landsat)
# Plot surface reflectance in RGB:
plotRGB(landsat, 3, 2, 1) # "natural" color
plotRGB(landsat, 4, 1, 2, stretch = "lin") # emphasize near-infrared (vegetation)
# Make composite map from RGB layers and plot in grayscale:
comp <- compositeRGB(r = landsat[[3]], g = landsat[[2]], b = landsat[[1]])
grays <- paste0("gray", 0:100)
plot(comp, col = grays)
}
Combine values/categories of multiple GRasters into a single GRaster
Description
This function takes from 2 to 10 integer or categorical (factor) GRaster
s and creates a single GRaster
that has one value per combination of values in the inputs. For example, say that there were two input rasters, with values 1 and 2 in the one raster, and 3 and 4 in the other. If the following combinations of values occurred between the two rasters, then the output raster would be re-coded with the new values:
input_raster1 | input_raster2 | output_raster |
1 | 3 | 0 |
1 | 4 | 1 |
2 | 3 | 2 |
2 | 4 | 3 |
If the argument na.rm
is set to TRUE
(which it is, by default), then whenever at least one cell has an NA
value, then the output will also have an NA
(i.e., a new category number is not created). However, if na.rm
is FALSE
, then combinations that include an NA
are assigned a new category number, unless all values are NA
(in which case the output will be NA
).
The difference between this function and combineLevels()
is that this one creates a "combined" GRaster
with a combined levels table, whereas combineLevels()
just merges the levels tables.
If the inputs are all categorical rasters, then a levels()
table will also be returned with the new levels.
Usage
## S4 method for signature 'GRaster'
concats(x, ..., na.rm = TRUE)
Arguments
x |
A |
... |
Either missing or integer/categorical (factor) |
na.rm |
Logical: If |
Value
A GRaster
. If the inputs are all categorical (factor) rasters, then a levels table will also be returned with the new combined levels.
See Also
combineLevels()
, terra::concats()
, vignette("GRasters", package = "fasterRaster")
, GRASS manual page for tool r.cross
(see grassHelp("r.cross")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Create lines connecting nearest features of two GVectors
Description
connectors()
creates a lines GVector
which represent the shortest (Great Circle) paths between each feature of one GVector
and the nearest feature of another GVector
.
Usage
## S4 method for signature 'GVector,GVector'
connectors(x, y, minDist = NULL, maxDist = NULL)
Arguments
x , y |
|
minDist , maxDist |
Either |
Value
A GVector
with a data table that has the length of each connecting line in meters.
See Also
GRASS manual for tool v.distance
(see grassHelp("v.distance")
).
Examples
if (grassStarted()) {
# Setup
library(sf)
# Rivers vector and locations of Dypsis plants
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf's to GVectors:
dypsis <- fast(madDypsis)
rivers <- fast(madRivers)
### Connections from each point to nearest river
consFromDypsis <- connectors(dypsis, rivers)
plot(rivers, col = "blue")
plot(dypsis, add = TRUE)
plot(consFromDypsis, col = "red", add = TRUE)
### Connections from each river to nearest point
consFromRivers <- connectors(rivers, dypsis)
plot(rivers, col = "blue")
plot(dypsis, add = TRUE)
plot(consFromRivers, col = "red", add = TRUE)
}
Minimum convex hull around a spatial vector
Description
Create a minimum convex hull around a spatial vector.
Usage
## S4 method for signature 'GVector'
convHull(x, by = "")
Arguments
x |
A |
by |
Character: If |
Value
A GVector
.
See Also
link[terra]{convHull}
, link[sf]{st_convex_hull}
, tool v.hull
in GRASS (see grassHelp("v.hull")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
# Points vector of specimens of species in the plant genus Dypsis
madDypsis <- fastData("madDypsis")
# Convert sf to a GVector:
dypsis <- fast(madDypsis)
### Convex hull for all plant specimens together:
ch <- convHull(dypsis)
### Convex hull for each species:
head(dypsis) # See the "rightsHolder" column?
chHolder <- convHull(dypsis, by = "rightsHolder")
### Plot:
plot(dypsis)
plot(ch, add = TRUE)
n <- length(chHolder)
for (i in 1:n) {
plot(chHolder[[i]], border = i, add = TRUE)
}
}
Coordinates of a vector"s features or a raster"s cell centers
Description
Returns the coordinates of the center of cells of a GRaster
or coordinates of a GVector
's vertices. The output will be a matrix
, data.frame
, or list
. If you want the output to be a "points" GVector
, use as.points()
.
Usage
## S4 method for signature 'GRaster'
crds(x, z = is.3d(x), na.rm = TRUE)
## S4 method for signature 'GVector'
crds(x, z = is.3d(x))
st_coordinates(x)
Arguments
x |
A |
z |
If |
na.rm |
Logical: If |
Value
A matrix
, data.frame
, or list
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Plant specimens (points), elevation (raster)
madDypsis <- fastData("madDypsis")
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster, and sf to a GVector
dypsis <- fast(madDypsis)
elev <- fast(madElev)
### Get coordinates:
dypsisPoints <- crds(dypsis)
elevPoints <- crds(elev)
head(dypsisPoints)
head(elevPoints)
}
Remove parts of a GRaster or GVector
Description
crop()
removes parts of a GRaster
or GVector
that fall "outside" another raster or vector. You cannot make the GRaster
or GVector
larger than it already is (see extend()
). Rasters may not be cropped to the exact extent, as the extent will be enlarged to encompass an integer number of cells. If you wish to remove certain cells of a raster, see mask()
.
Usage
## S4 method for signature 'GRaster'
crop(x, y, fail = TRUE)
## S4 method for signature 'GVector'
crop(x, y, extent = FALSE, fail = TRUE)
Arguments
x |
A |
y |
A |
fail |
Logical: If |
extent |
Logical:
|
Details
Known differences from terra::crop()
:
If
x
andy
are "points" vectors, andextent
isTRUE
, terra removes points that fall on the extent boundary. fasterRaster does not remove points on the extent boundary.If
x
is a "points" vector andy
is a "lines" vectors, andextent
isFALSE
, terra uses the extent ofy
to crop the points. fasterRaster uses the minimum convex hull of the lines vector.
Value
A GRaster
or GVector
(or NULL
if fail
is FALSE
and the output would have a zero east-west and/or north-south extent).
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Plant specimen points vector
madDypsis <- fastData("madDypsis")
# Rivers lines vector
madRivers <- fastData("madRivers")
# Polygons vector
madCoast4 <- fastData("madCoast4")
madAnt <- madCoast4[madCoast4$NAME_4 == "Antanambe", ]
# Convert to fasterRaster format:
elev <- fast(madElev)
dypsis <- fast(madDypsis)
rivers <- fast(madRivers)
coast <- fast(madCoast4)
ant <- fast(madAnt)
### Crop raster by vector:
rastByVect <- crop(elev, ant)
plot(elev, col = "gray", legend = FALSE)
plot(rastByVect, add = TRUE)
plot(ant, add = TRUE)
### Crop raster by raster:
# For this example, make the SpatRaster smaller, then crop by this.
templateRast <- crop(madElev, madAnt)
template <- fast(templateRast)
rastByRast <- crop(elev, template)
plot(elev, col = "gray", legend = FALSE)
plot(rastByRast, add = TRUE)
### Crop vector by raster:
# For this example, make the SpatRaster smaller, then crop by this.
templateRast <- crop(madElev, madAnt)
template <- fast(templateRast)
ptsByRast <- crop(dypsis, template)
plot(elev, col = "gray", legend = FALSE)
plot(templateRast, add = TRUE)
plot(dypsis, add = TRUE)
plot(ptsByRast, pch = 21, bg = "red", add = TRUE)
### Crop vector by vector:
ptsSubset <- dypsis[1:10] # use first 10 points as cropping template
# Crop points vector by convex hull around points:
ptsByPts <- crop(dypsis, ptsSubset)
plot(dypsis)
plot(convHull(ptsSubset), lty = "dotted", border = "blue", add = TRUE)
plot(ptsByPts, col = "red", add = TRUE)
plot(ptsSubset, col = "blue", pch = 3, cex = 1.6, add = TRUE)
legend("topleft",
legend = c("Dypsis", "Selected", "Crop template", "Convex hull"),
pch = c(16, 16, 3, NA),
lwd = c(NA, NA, NA, 1),
col = c("black", "red", "blue", "blue"),
lty = c(NA, NA, NA, "dotted"),
xpd = NA,
bg = "white"
)
# Crop points vector by extent of points:
ptsByPts <- crop(dypsis, ptsSubset, ext = TRUE)
plot(dypsis)
plot(ptsByPts, col = "red", add = TRUE)
plot(ptsSubset, col = "blue", pch = 3, cex = 1.6, add = TRUE)
legend("topleft",
legend = c("Dypsis", "Selected", "Crop template"),
pch = c(16, 16, 3),
lwd = c(NA, NA, NA),
col = c("black", "red", "blue"),
lty = c(NA, NA, NA),
xpd = NA,
bg = "white"
)
# Crop points vector by convex hull around lines:
ptsByPts <- crop(dypsis, rivers)
plot(rivers, col = "blue", pch = 3, cex = 1.6)
plot(dypsis, add = TRUE)
plot(convHull(rivers), lty = "dotted", border = "blue", add = TRUE)
plot(ptsByPts, col = "red", add = TRUE)
legend("topleft",
legend = c("Dypsis", "Selected", "Rivers", "Convex hull"),
pch = c(16, 16, NA, NA),
lwd = c(NA, NA, 1, 1),
col = c("black", "red", "blue", "blue"),
lty = c(NA, NA, "solid", "dotted"),
xpd = NA,
bg = "white"
)
# Crop points vector by extent of lines:
ptsByPts <- crop(dypsis, rivers, ext = TRUE)
plot(rivers, col = "blue", pch = 3, cex = 1.6)
plot(dypsis, add = TRUE)
plot(convHull(rivers), lty = "dotted", border = "blue", add = TRUE)
plot(ptsByPts, col = "red", add = TRUE)
legend("topleft",
legend = c("Dypsis", "Selected", "Rivers"),
pch = c(16, 16, NA),
lwd = c(NA, NA, 1),
col = c("black", "red", "blue"),
lty = c(NA, NA, "solid"),
xpd = NA,
bg = "white"
)
# Crop points vector by polygon:
ptsByPts <- crop(dypsis, ant)
plot(dypsis)
plot(ant, border = "blue", pch = 3, cex = 1.6, add = TRUE)
plot(ptsByPts, col = "red", add = TRUE)
legend("topleft",
legend = c("Dypsis", "Selected", "Antanambe"),
pch = c(16, 16, NA),
lwd = c(NA, NA, 1),
col = c("black", "red", "blue"),
lty = c(NA, NA, "solid"),
xpd = NA,
bg = "white"
)
# Crop lines vector by polygon:
linesByPoly <- crop(rivers, ant)
plot(rivers)
plot(ant, border = "blue", pch = 3, cex = 1.6, add = TRUE)
plot(linesByPoly, col = "red", add = TRUE)
legend("topleft",
legend = c("Rivers", "Selected", "Antanambe"),
col = c("black", "red", "blue"),
lwd = 1,
xpd = NA,
bg = "white"
)
# Crop polygon vector by convex hull around points:
polyByPoints <- crop(ant, dypsis)
plot(dypsis, col = "red")
plot(ant, border = "blue", add = TRUE)
plot(polyByPoints, border = "red", add = TRUE)
legend("topleft",
legend = c("Dypsis", "Antanambe", "Selected"),
col = c("red", "blue", "red"),
pch = c(16, NA, NA),
lwd = c(NA, 1, 1),
xpd = NA,
bg = "white"
)
}
Coordinate reference system of a GRaster or GVector
Description
Get the coordinate reference system (CRS) of a GRaster
or GVector
s, or from the currently active GRASS "project/location" (see vignette("projects_mapsets", package = "fasterRaster")
):
-
crs()
: Return a WKT string (an object of classcharacter
). -
st_crs()
: Return acrs
object (from the sf package). -
coordRef()
: Return alist
.
Usage
## S4 method for signature 'missing'
crs(x)
## S4 method for signature 'GLocation'
crs(x)
## S4 method for signature 'missing'
st_crs(x, ...)
## S4 method for signature 'GLocation'
st_crs(x, ...)
st_crs(x, ...)
## S4 method for signature 'missing'
coordRef(x)
## S4 method for signature 'GRaster'
coordRef(x)
## S4 method for signature 'GVector'
coordRef(x)
Arguments
x |
An object that inherits from a |
... |
Other arguments (generally unused). |
Value
Function crs()
returns a character
object, st_crs()
returns crs
object, and coordRef()
a list
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Get the datatype of a GRaster or of GVector columns
Description
For GRaster
s, datatype()
returns the data type (see vignette("GRasters", package = "fasterRaster")
). For GVector
s, datatype()
returns the class of each column of the attribute table.
Usage
## S4 method for signature 'GRaster'
datatype(x, type = "fasterRaster", forceDouble = TRUE)
## S4 method for signature 'GVector'
datatype(x)
Arguments
x |
A |
type |
(
|
forceDouble |
Logical ( |
Value
datatype()
for a GRaster
returns a character. datatype()
for a GVector
returns a data frame, with one row per field. If the GVector
has no attribute table, the function returns NULL
.
See Also
terra::datatype()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Delaunay triangulation for points
Description
This function creates a Delaunay triangulation from a "points" GVector
.
Usage
## S4 method for signature 'GVector'
delaunay(x)
Arguments
x |
A |
Value
A GVector
.
See Also
terra::delaunay()
, tool v.delaunay
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example vectors
madDypsis <- fastData("madDypsis") # points
madCoast4 <- fastData("madCoast4") # polygons
# Convert sf vectors to GVectors
dypsis <- fast(madDypsis)
coast4 <- fast(madCoast4)
ant <- coast4[coast4$NAME_4 == "Antanambe"]
# Delaunay triangulation
dypsisDel <- delaunay(dypsis)
plot(dypsisDel)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Voronoi tessellation
vor <- voronoi(dypsis)
plot(vor)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Random Voronoi tessellation
rand <- rvoronoi(coast4, size = 100)
plot(rand)
}
Remove or retain "noise" in a raster using PCA
Description
denoise()
applies a principal component analysis (PCA) to layers of a GRaster
, then uses the PCA to predict values back to a raster. This retains only coarse-scale trends, thereby removing "noise" (locally extreme values that fall far from a PC axis).
noise()
does the opposite by first constructing the PCA, predicting values back to the raster, then subtracting these values from the original, removing coarse-scale trends and thereby leaving "noise".
Usage
## S4 method for signature 'GRaster'
denoise(x, scale = FALSE, percent = 80)
## S4 method for signature 'GRaster'
noise(x, scale = FALSE, percent = 80)
Arguments
x |
A |
scale |
Logical: If |
percent |
Numeric integer or integer in the range 50 to 99 (default is 80): Minimum total variation explained in the retained PC axes. Higher values will cause |
Value
A multi-layer GRaster
with one layer per input.
See Also
princomp()
, stats::prcomp()
, GRASS manual page for tool i.pca
(see grassHelp("i.pca")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Climate raster:
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster:
chelsa <- fast(madChelsa)
### Denoise:
quiet <- denoise(chelsa, scale = TRUE)
compare1 <- c(chelsa[["bio1"]], quiet[["bio1"]])
plot(compare1)
compare2 <- c(chelsa[["bio7"]], quiet[["bio7"]])
plot(compare2)
### Noise:
loud <- noise(chelsa, scale = TRUE)
compare1 <- c(chelsa[["bio1"]], loud[["bio1"]])
plot(compare1)
compare2 <- c(chelsa[["bio7"]], loud[["bio7"]])
plot(compare2)
}
Number of rows, columns, depths, cells, and layers
Description
For GRegion
s: Number of rows, columns, depths, and cells:
-
dim()
: Rows and columns -
dim3d()
: Rows, columns, and depths -
nrow()
: Rows -
ncol()
: Columns -
ndepth()
: Depths (for 3-dimensional rasters only) -
ncell()
: Number of cells (2 dimensions) -
ncell3d()
: Number of cells (3 dimensions)
For GRaster
s: As above, plus number of layers:
-
nlyr()
: Layers (number of "stacked" rasters–different from depths of a raster).
For GVector
s: Number of geometries and fields (columns):
-
dim()
: Number of geometries and number of columns in data table -
nrow()
: Number of geometries -
ncol()
: Number of columns in data table
Usage
## S4 method for signature 'GRegion'
dim(x)
## S4 method for signature 'missing'
dim3d(x)
## S4 method for signature 'GRegion'
dim3d(x)
## S4 method for signature 'missing'
nrow(x)
## S4 method for signature 'GRegion'
nrow(x)
## S4 method for signature 'missing'
ncol(x)
## S4 method for signature 'GRegion'
ncol(x)
## S4 method for signature 'missing'
ndepth(x)
## S4 method for signature 'GRegion'
ndepth(x)
## S4 method for signature 'missing'
ncell(x)
## S4 method for signature 'GRegion'
ncell(x)
## S4 method for signature 'missing'
ncell3d(x)
## S4 method for signature 'GRegion'
ncell3d(x)
## S4 method for signature 'GVector'
dim(x)
## S4 method for signature 'GVector'
nrow(x)
## S4 method for signature 'GVector'
ncol(x)
## S4 method for signature 'missing'
nlyr(x)
## S4 method for signature 'GRaster'
nlyr(x)
Arguments
x |
A |
Value
A numeric value or vector.
See Also
ngeom()
, nsubgeom()
, nacell()
, nonnacell()
, terra::dim()
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Coerce as multipart GVector to a singlepart GVector
Description
GVectors
can contain a mix of "singlepart" and "multipart" features. A singlepart feature is a single point, set of connected line segments, or a polygon. A multipart feature is a set of lines, sets of connected line segments, or set of polygons that are treated as a single feature. This function converts all multipart features to singlepart features. If the GVector
has an attribute table, rows will be duplicated so that each of the new GVector
's geometries have the rows that correspond to their "parent" geometries.
If you want to "split" cells of a GRaster
into smaller cells, use aggregate()
.
Usage
## S4 method for signature 'GVector'
disagg(x)
Arguments
x |
A |
Value
A GVector
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madCoast4 <- fastData("madCoast4")
### aggregating a GRaster
# Convert:
elev <- fast(madElev)
### Aggregate GRaster by same factor in 2 dimensions
# fasterRaster
agg2 <- aggregate(elev, 2, "mean")
agg2
# Compare rasters aggregated by fasterRaster and terra.
# These should be the same.
agg2terra <- aggregate(madElev, 2)
agg2 <- rast(agg2)
agg2 <- extend(agg2, agg2terra)
agg2 - agg2terra # value is ~0
### Aggregate GRaster by a non-integer factor in 2 dimensions
# fasterRaster
agg2.9 <- aggregate(elev, 2.9, "mean")
agg2.9
# terra
agg2.9terra <- aggregate(madElev, 2.9, "mean")
agg2.9terra
# Compare rasters aggregated by fasterRaster and terra.
# These should be different.
res(agg2.9)
res(agg2.9terra) # terra rounds aggregation factor down
2 * res(madElev) # original resolution multiplied by 2
### Aggregate GRaster by different factor in 2 dimensions
agg2x3 <- aggregate(elev, c(2, 3), "mean")
agg2x3
### aggregating a GVector
madCoast4 <- fastData("madCoast4")
# Convert:
coast4 <- fast(madCoast4)
# Aggregate and disaggregate:
aggCoast <- aggregate(coast4)
disaggCoast <- disagg(coast4)
ngeom(coast4)
ngeom(aggCoast)
ngeom(disaggCoast)
# plot
oldpar <- par(mfrow = c(1, 3))
plot(coast4, main = "Original", col = 1:nrow(coast4))
plot(aggCoast, main = "Aggregated", col = 1:nrow(aggCoast))
plot(disaggCoast, main = "Disaggregated", col = 1:nrow(disaggCoast))
par(oldpar)
}
Geographic distance
Description
This function produces a raster or a matrix of geographic distances, depending on the input:
Case 1: Argument x
is a GRaster
and y
is missing: By default, this function replaces values in all NA
cells with the distance between them and their closest non-NA
cell. Alternatively, all non-NA
cells can have their values replaced by the distance to NA
cells. You can also specify which cells (by value) have their values replaced by distance to other cells.
Case 2: Argument x
is a GRaster
and y
is a GVector
: All cells in the raster have their value replaced by the distance to the nearest features in the GVector
. Alternatively, calculate the distance from any cell covered by a vector object and the nearest cell not covered by a vector object. Note that the vector is rasterized first.
Case 3: Argument x
is a GVector
and y
is a GVector
: A matrix of pairwise distances between all features in one versus the other GVector
is returned.
Case 4: Argument x
is a GVector
and y
is missing: A matrix of pairwise distances between all features in the GVector
is returned.
Usage
## S4 method for signature 'GRaster,missing'
distance(
x,
y,
target = NA,
fillNA = TRUE,
unit = "meters",
method = ifelse(is.lonlat(x), "geodesic", "Euclidean"),
minDist = NULL,
maxDist = NULL
)
## S4 method for signature 'GRaster,GVector'
distance(
x,
y,
fillNA = TRUE,
thick = TRUE,
unit = "meters",
method = ifelse(is.lonlat(x), "geodesic", "Euclidean"),
minDist = NULL,
maxDist = NULL
)
## S4 method for signature 'GVector,GVector'
distance(x, y, unit = "meters", minDist = NULL, maxDist = NULL)
## S4 method for signature 'GVector,missing'
distance(x, y, unit = "meters", minDist = NULL, maxDist = NULL)
Arguments
x |
A |
y |
Either missing, or a |
target |
Numeric: Only applicable for case 1, when |
fillNA |
Logical: Determines which raster cells to fill with distances.
|
unit |
Character: Units of the output. Any of:
Partial matching is used and case is ignored. |
method |
Character: The type of distance to calculate. Partial matching is used and capitalization is ignored. Possible values include:
|
minDist , maxDist |
Either |
thick |
Logical: Only applicable for case 2, when |
Value
If x
is a GRaster
, then the output is a GRaster
. If x
is a GVector
, then the output is a numeric vector.
See Also
terra::distance()
; GRASS modules r.grow.distance
and v.distance
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster, rivers vector, locations of Dypsis plants
madElev <- fastData("madElev")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert a SpatRaster to a GRaster, and sf to a GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
### case 1: GRaster by itself
# Distance between NA cells and nearest non-NA cells
naDist <- distance(elev)
names(naDist) <- "NA Distance"
plot(naDist)
# Distance between non-NA cells and nearest NA cells
nonNaDist <- distance(elev, fillNA = FALSE)
names(nonNaDist) <- "non-NA Distance"
plot(nonNaDist)
# Distance between cells with an elevation of 3 and any other cell that != 3
distFocal3 <- distance(elev, target = 3)
names(distFocal3) <- "Distance from 3"
plot(distFocal3)
# Distance between any cell and cells with a value of 3
distTo3 <- distance(elev, fillNA = FALSE, target = 3)
names(distTo3) <- "Distance to 3"
plot(distTo3)
### Case 2: GRaster and GVector
distToVect <- distance(elev, rivers)
plot(distToVect)
plot(rivers, add = TRUE)
### Case 3: GVector vs GVector
plot(rivers)
plot(dypsis, add = TRUE)
distToRivers <- distance(dypsis, rivers, unit = "yd")
distToPlants <- distance(rivers, dypsis)
distToRivers
distToPlants
### Case 4: GVector vs itself
distToItself <- distance(dypsis)
distToItself
}
Remove rows in a data.table, data.frame, or matrix.
Description
As of September of 2023, the data.table package does not have a function for removing rows by index. This function does this job.
Usage
## S4 method for signature 'data.table'
dropRows(x, drops)
## S4 method for signature 'data.frame'
dropRows(x, drops)
## S4 method for signature 'matrix'
dropRows(x, drops)
Arguments
x |
A |
drops |
Numeric, integer, or logical vector: Indices or indicators of rows to remove. If a logical vector is supplied, rows that correspond to |
Value
A data.table
or data.frame
.
Examples
library(data.table)
dt <- data.table(
x = 1:10,
y = letters[1:10],
z = rnorm(10)
)
# make some values NA
dt[x == 4 | x == 8, y := NA_character_]
dt
# Replace NAs:
replaceNAs(dt, replace = -99, cols = "y")
dt
# Drop rows:
dropped <- dropRows(dt, 8:10)
dropped
# NB May not print... in that case, use:
print(dropped)
# We can also use replaceNAs() on vectors:
y <- 1:10
y[c(2, 10)] <- NA
replaceNAs(y, -99)
# Same as:
y <- 1:10
y[c(2, 10)] <- NA
y[is.na(y)] <- -99
Remove rows from the "levels" table of a categorical raster
Description
droplevels()
removes levels (category values) from the "levels" table of a categorical GRaster
.
Usage
## S4 method for signature 'GRaster'
droplevels(x, level = NULL, layer = 1)
Arguments
x |
A |
level |
|
layer |
Numeric integers, logical vector, or character: Layer(s) to which to add or from which to drop levels. |
Value
A GRaster
. The "levels" table of the raster is modified.
See Also
missingCats()
, missing.cases()
, terra::droplevels()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Select parts of a polygon GVector erase shared by another polygon GVector
Description
The erase()
function removes from the x
"polygons" GVector
parts that overlap with the y
"polygons" GVector
. You can also use the -
operator (e.g., vect1 - vect2
).
Usage
## S4 method for signature 'GVector,GVector'
erase(x, y)
Arguments
x , y |
|
Value
A GVector
.
See Also
c()
, aggregate()
, crop()
, intersect()
, union()
, xor()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Polygon of coastal Madagascar and Dypsis specimens
madCoast4 <- fastData("madCoast4") # polygons
madDypsis <- fastData("madDypsis") # points
# Convert vectors:
coast4 <- fast(madCoast4)
dypsis <- fast(madDypsis)
# Create another polygons vector from a convex hull around Dypsis points
hull <- convHull(dypsis)
### union()
unioned <- union(coast4, hull)
plot(unioned)
plus <- coast4 + hull # same as union()
### intersect
inter <- intersect(coast4, hull)
plot(coast4)
plot(hull, border = "red", add = TRUE)
plot(inter, border = "blue", add = TRUE)
### xor
xr <- xor(coast4, hull)
plot(coast4)
plot(xr, border = "blue", add = TRUE)
### erase
erased <- erase(coast4, hull)
plot(coast4)
plot(erased, border = "blue", add = TRUE)
minus <- coast4 - hull # same as erase()
}
Area of polygons or length of lines
Description
This function calculates the area of each polygon in a "polygons" GVector
or the length of lines in a "lines" GVector
.
Usage
## S4 method for signature 'GVector'
expanse(x, unit = "m")
Arguments
x |
A "polygons" or "lines" |
unit |
Character: Units in which to report values. Areal units are squared, linear are not. Can be any of:
Partial matching is used and case is ignored. |
Value
Numeric values, one per geometry in x
.
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Spatial bounds of a GRaster or GVector
Description
These functions return the extent of a GSpatial
object (GRegions
, GRaster
s, and GVector
s):
-
ext()
: 2-dimensional spatial extent (i.e., westernmost/easternmost and southernmost/northernmost coordinates of area represented).
-
zext()
: Vertical extent (i.e., topmost and bottom-most elevation of the volume represented). The vertical extent is notNA
only if the object is 3-dimensional.
-
W()
,E()
,N()
,S()
: Coordinates of one side of horizontal extent.
-
top()
andbottom()
: Coordinates of top and bottom of vertical extent.
Usage
## S4 method for signature 'missing'
ext(x, vector = FALSE)
## S4 method for signature 'GSpatial'
ext(x, vector = FALSE)
## S4 method for signature 'missing'
zext(x)
## S4 method for signature 'GSpatial'
zext(x)
## S4 method for signature 'missing'
W(x, char = FALSE)
## S4 method for signature 'GSpatial'
W(x, char = FALSE)
## S4 method for signature 'missing'
E(x, char = FALSE)
## S4 method for signature 'GSpatial'
E(x, char = FALSE)
## S4 method for signature 'missing'
N(x, char = FALSE)
## S4 method for signature 'GSpatial'
N(x, char = FALSE)
## S4 method for signature 'missing'
S(x, char = FALSE)
## S4 method for signature 'GSpatial'
S(x, char = FALSE)
## S4 method for signature 'missing'
top(x, char = FALSE)
## S4 method for signature 'GSpatial'
top(x, char = FALSE)
## S4 method for signature 'GSpatial'
bottom(x, char = FALSE)
## S4 method for signature 'GSpatial'
bottom(x, char = FALSE)
Arguments
x |
An object that inherits from |
vector |
Logical: If |
char |
Logical: If |
Value
The returned values depend on the function:
-
ext()
: ASpatExtent
object (terra package) or a numeric vector. -
zext()
: A numeric vector. -
W()
,E()
,N()
,S()
,top()
, andbottom()
: A numeric value or character.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Add rows and columns around a writeRaster
Description
extend()
adds cells around a raster, making it larger.
Usage
## S4 method for signature 'GRaster,numeric'
extend(x, y, fill = NA)
## S4 method for signature 'GRaster,SpatRaster'
extend(x, y, snap = "near", fill = NA)
## S4 method for signature 'GRaster,SpatVector'
extend(x, y, snap = "near", fill = NA)
## S4 method for signature 'GRaster,SpatExtent'
extend(x, y, snap = "near", fill = NA)
## S4 method for signature 'GRaster,sf'
extend(x, y, snap = "near", fill = NA)
## S4 method for signature 'GRaster,GSpatial'
extend(x, y, snap = "near", fill = NA)
Arguments
x |
A |
y |
Any of:
|
fill |
Numeric: Value to place in the new cells. The default is |
snap |
Character: Method used to align
|
Details
Known issues: When GRaster
s are saved to disk explicitly using writeRaster()
, or implicitly using rast()
or plot()
, rows and columns that are entirely NA
are dropped.
Value
A GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madRivers <- fastData("madRivers")
# Send spatial objects to GRASS:
elev <- fast(madElev)
rivers <- fast(madRivers)
# Extend raster by number of rows/columns:
extended1 <- extend(elev, 10, fill = 900)
extended2 <- extend(elev, c(10, 20), fill = 900)
extended3 <- extend(elev, c(10, 80, 0, 100), fill = 900)
dim(elev)
dim(extended1)
dim(extended2)
dim(extended3)
plot(extended3)
# When exporting a raster, NA rows and columns are removed.
extended4 <- extend(elev, 100, fill=1) # default fill is NA
extended4terra <- rast(extended4)
dim(extended4)
dim(extended4terra)
plot(extended4)
# Extend the raster by another object with a wider extent.
# For tis example, first crop the raster, then extend it.
elevCrop <- crop(elev, rivers)
uncrop <- extend(elevCrop, elev, fill = 900)
plot(uncrop)
}
Extract values from a GRaster at locations in a points GVector
Description
extract()
obtains the values of a GRaster
or GVector
associated with the locations of a set of points. The output depends on the input:
-
Case #1:
x
is a numeric or integerGRaster
andy
is a pointsGVector
: Returns values of cells that have points. Ifxy
isTRUE
, also returns the coordinates of the points. -
Case #2:
x
is a categorical (factor)GRaster
andy
is a pointsGVector
: Same as case #1, but ifcats
isTRUE
, returns category labels of cells that have points. Ifxy
isTRUE
, also returns the coordinates of the points. -
Case #3:
x
is a categoricalGRaster
andy
is a lines or polygonsGVector
: Returns a summary (e.g., mean, standard deviation, etc.) of all cells that overlap the line(s) or polygon(s). -
Case #4:
x
is aGVector
andy
is a pointsGVector
: Returns the data table row associated each point. Ifxy
isTRUE
, also returns the coordinates of the points. Note that whenever a pointsGVector
is allowed fory
, adata.frame
,data.table
,matrix
, ornumeric
values representing points can be used instead.
Usage
## S4 method for signature 'GRaster,GVector'
extract(
x,
y,
fun = "mean",
prob = 0.5,
overlap = TRUE,
xy = FALSE,
cats = TRUE,
verbose = FALSE,
...
)
## S4 method for signature 'GRaster,data.frame'
extract(x, y, xy = FALSE, cats = TRUE)
## S4 method for signature 'GRaster,data.table'
extract(x, y, xy = FALSE, cats = TRUE)
## S4 method for signature 'GRaster,matrix'
extract(x, y, xy = FALSE, cats = TRUE)
## S4 method for signature 'GRaster,numeric'
extract(x, y, xy = FALSE, cats = TRUE)
## S4 method for signature 'GVector,GVector'
extract(x, y, xy = FALSE, verbose = TRUE)
## S4 method for signature 'GVector,data.frame'
extract(x, y, xy = FALSE, verbose = TRUE)
## S4 method for signature 'GVector,data.table'
extract(x, y, xy = FALSE, verbose = TRUE)
## S4 method for signature 'GVector,matrix'
extract(x, y, xy = FALSE, verbose = TRUE)
## S4 method for signature 'GVector,numeric'
extract(x, y, xy = FALSE)
Arguments
x |
A |
y |
A |
fun |
Character vector: Name(s) of function(s) to apply to values. This is used when
|
prob |
Numeric in the range from 0 to 1: Quantile which to calculate. The value of |
overlap |
Logical: If |
xy |
Logical: If |
cats |
Logical (extracting from a raster): If |
verbose |
Logical: If |
... |
Arguments to pass to |
Value
A data.frame
or data.table
.
See Also
terra::extract()
, and modules r.what
and v.what
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data: elevation raster and points vector
madElev <- fastData("madElev") # raster
madCover <- fastData("madCover") # categorical raster
madDypsis <- fastData("madDypsis") # points vector
madRivers <- fastData("madRivers") # lines vector
madCoast4 <- fastData("madCoast4") # polygons vector
# Convert to fasterRaster formats:
elev <- fast(madElev) # raster
cover <- fast(madCover) # categorical raster
dypsis <- fast(madDypsis) # points vector
rivers <- fast(madRivers) # lines vector
coast <- fast(madCoast4) # polygons vector
# Get values of elevation at points where Dypsis species are located:
extract(elev, dypsis, xy = TRUE)
# Extract from categorical raster at points:
categories <- extract(cover, dypsis)
categoryValues <- extract(cover, dypsis, cats = FALSE)
categories
categoryValues
# Extract and summarize values on a raster across polygons:
extract(elev, coast, fun = c("sum", "mean", "countNonNA"), overlap = FALSE)
# Extract and summarize values on a raster across lines:
extract(elev, rivers, fun = c("sum", "mean", "countNonNA"), overlap = FALSE)
# Extract from a polygons vector at a points vector:
polysFromPoints <- extract(coast, dypsis, xy = TRUE)
head(polysFromPoints) # first 3 are outside polygons vector, next 3 are inside
}
Create a GRaster or GVector
Description
fast()
creates a GRaster
or GVector
from 1) a file; 2) from a SpatRaster
, SpatVector
, or sf
vector; or 3) from a numeric vector, matrix
, data.frame
, or data.table
. Behind the scenes, this function will also create a connection to GRASS if none has yet been made yet.
GRASS supports loading from disk a variety of raster formats (see the GRASS manual page for r.in.gdal
(see grassHelp("r.in.gdal")
) and vector formats v.in.ogr
(see grassHelp("v.in.ogr")'), though not all of them will work with this function.
Note that GVectors
may fail to be created if they contain issues that do not coincide with the topological data model used by GRASS. The most common of these is overlapping polygons. See Details on how to fix these kinds of issues.
Note also that GRASS (and thus, fasterRaster) is not very fast when loading vectors. So, if the vector is large and you only want a portion of it, consider using the extent
argument to load the spatial subset you need.
Usage
## S4 method for signature 'character'
fast(
x,
rastOrVect = NULL,
levels = TRUE,
extent = NULL,
correct = TRUE,
snap = NULL,
area = NULL,
steps = 10,
dropTable = FALSE,
resolve = NA,
verbose = TRUE,
...
)
## S4 method for signature 'SpatRaster'
fast(x, ...)
## S4 method for signature 'SpatVector'
fast(
x,
extent = NULL,
correct = TRUE,
snap = NULL,
area = NULL,
steps = 10,
dropTable = FALSE,
resolve = NA,
verbose = TRUE
)
## S4 method for signature 'sf'
fast(
x,
extent = NULL,
correct = TRUE,
snap = NULL,
area = NULL,
steps = 10,
resolve = NA,
dropTable = FALSE,
verbose = TRUE
)
## S4 method for signature 'missing'
fast(x, rastOrVect, crs = "")
## S4 method for signature 'numeric'
fast(x, crs = "", keepgeom = FALSE)
## S4 method for signature 'data.frame'
fast(x, geom = 1:2, crs = "", keepgeom = FALSE)
## S4 method for signature 'data.table'
fast(x, geom = 1:2, crs = "", keepgeom = FALSE)
## S4 method for signature 'matrix'
fast(x, geom = 1:2, crs = "", keepgeom = FALSE)
Arguments
x |
Any one of:
|
rastOrVect |
Either |
levels |
(
|
extent |
( |
correct |
Logical ( |
snap |
|
area |
Polygon |
steps |
|
dropTable |
|
resolve |
|
verbose |
|
... |
Other arguments::
|
crs |
String: Coordinate reference system (CRS) WKT2 string. This argument is used for creating a |
keepgeom |
Logical: If |
geom |
Character or integer vector: If |
Details
GRASS uses a "topological" model for vectors. Topological issues generally arise only with polygon vectors, not point or line vectors. Sometimes, polygons created in other software are topologically incorrect–the borders of adjacent polygons may cross one another, or there may be small gaps between them. These errors can be corrected by slightly shifting vertices and/or removing small polygons that result from intersections of larger ones that border one another. A topological system also recognizes that boundaries to adjacent polygons are shared by the areas, so should not be ascribed attributes that belong to both areas (e.g., the shared border between two countries "belongs" to both countries).
By default, fast()
will try to correct topological errors in vectors. There are three levels of correction, and they are not necessarily mutually exclusive:
-
Automatic correction: By default,
fast()
will apply automatic topology correction. You can turn this off using thecorrect = FALSE
argument, though in most cases this is not recommended. -
Manual snapping and/or area removal: In addition to correction from step 1, you can cause vertices of polygons close to one another to be "snapped" to same place and/or polygons that are smaller than some threshold to be removed. Problems with mis-aligned vertices arise when adjacent polygons are meant to share borders, but slight differences in the locations of the vertices cause them to mis-align. This mis-alignment can also produce small "slivers" of polygons that are the areas where they overlap. You can snap vertices within a given distance of one another using the
snap
argument followed by a numeric value, likesnap = 0.000001
. Units ofsnap
are in map units (usually meters) for projected coordinate reference systems and degrees for unprojected systems (e.g., WGS84, NAD83, NAD27). You can also remove polygons that are smaller than a particular area using thearea
argument followed by a numeric value (e.g.,area = 1
). The units ofarea
are in meters-squared, regardless of the coordinate reference system. Note that usingsnap
andarea
entails some risk, as it is possible for nearby vertices to actually be distinct and for small areas to be legitimate. -
Automatic snapping and/or area removal: In addition to the correction from step 1, you can use automatic
snap
and/orarea
correction on polygons vectors by settingsnap
and/orarea
toNULL
(i.e., their default values). If justsnap
isNULL
, only automatic snapping will be performed, and if justarea
isNULL
, then only automatic area removal will be performed. Regardless, you will also need to set an integer value forsteps
, which is the number of steps to take between the smallest value ofsnap
and/orarea
and the maximum value attempted. The function will then proceed by first attemptingsnap = 0
and/orarea = 0
(i.e., no snapping or area removal). If this does not produce a topologically correct vector, GRASS will (internally) suggest a range forsnap
. Thefast()
function then createssteps
values from the lowest to the highest values of this range evenly-spaced along the log values of this range, then proceed to repeat the importing process until either the vector is imported correctly or the maximum value ofsnap
is reached and results in a failed topology. Smaller values ofstep
will result in more fine-grained attempts so are less likely to yield overcorrection, but can also take more time. The value ofarea
in automatic correction is set tosnap^2
. NB: Automated snapping and area removal are only performed on polygons vectors, even ifsnap
orarea
isNULL
. To snap lines or points, you must setsnap
equal to a numeric value. Thearea
correction is ignored for points and lines.
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 bysnap
andarea
. Aggregation/disaggregation will cause any associated data table to be dropped (it forcesdropTable
to beTRUE
). The default action is to do neither aggregation nor disaggregation (resolve = NA
). You can also do this outside fasterRaster usingterra::aggregate()
orterra::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 theterra::makeValid()
orsf::st_make_valid()
tools to fix issues, then usefast()
. You can also useterra::aggregate()
orterra::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 orfillHoles()
to fix issues.
Value
A GRaster
or GVector
.
See Also
read_RAST
and read_VECT
, vector cleaning, fillHoles()
, plus GRASS modules v.in.ogr
(see grassHelp("v.in.ogr")
) and r.import
(grassHelp("r.import")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev") # integer raster
madCover <- fastData("madCover") # categorical raster
madCoast4 <- fastData("madCoast4") # polygons vector
madRivers <- fastData("madRivers") # lines vector
madDypsis <- fastData("madDypsis") # points vector
### Create GRasters from SpatRasters
# Create an integer raster:
elev <- fast(madElev)
elev
# Create a categorical raster:
cover <- fast(madCover)
madCover
levels(madCover) # category levels
# Create a GRaster from a file on disk:
rastFile <- system.file("extdata", "madForest2000.tif", package = "fasterRaster")
forest2000 <- fast(rastFile)
forest2000
# Create a 1's raster that spans the world:
ones <- fast(rastOrVect = "raster", crs = "epsg:4326")
ones
### Create GVectors
# Create a GVector from an sf vector:
coast4 <- fast(madCoast4)
coast4
# Create a GVector from a SpatVector:
madRivers <- vect(madRivers)
class(madRivers)
rivers <- fast(madRivers)
rivers
# Create a GVector from a vector on disk:
vectFile <- system.file("extdata/shapes", "madCoast.shp",
package = "fasterRaster")
coast0 <- fast(vectFile)
coast0
# Import only Dypsis occurrences in a restricted area:
ant <- coast4[coast4$NAME_4 == "Antanambe"]
dypsisRestrict <- fast(madDypsis, extent = ant)
dypsis <- fast(madDypsis)
plot(coast4)
plot(ant, col = "gray80", add = TRUE)
plot(dypsis, add = TRUE)
plot(dypsisRestrict, col = "red", add = TRUE)
# Create a generic GVector that spans the world:
wallToWall <- fast(rastOrVect = "vector", crs = "epsg:4326") # WGS84
wallToWall
# Create a GVector from a numeric vector
pts <- c(-90.2, 38.6, -122.3, 37.9)
pts <- fast(pts, crs = "epsg:4326") # WGS84
# Create a GVector from a matrix (can also use data.frame or data.table):
mat <- matrix(c(-90.2, 38.6, -122.3, 37.9), ncol = 2, byrow = TRUE)
mat <- fast(mat, crs = "epsg:4326", keepgeom = TRUE) # WGS84
}
Get one of the example rasters or spatial vectors
Description
This function is a simple way to get example rasters or spatial vector datasets that come with fasterRaster.
Usage
fastData(x)
Arguments
x |
The name of the raster or spatial vector to get. All of these represent a portion of the eastern coast of Madagascar. Spatial vectors (objects of class
Rasters (objects of class
Data frames
|
Value
A SpatRaster
, sf
spatial vector, or a data.frame
.
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Set or get options shared across fasterRaster functions
Description
faster()
either sets or gets options used across fasterRaster functions. Its use can vary:
Get current values of a particular option: Use
faster("option_name")
. Values will remain unchanged.Get current values of all options: Use
faster()
(no arguments). Values will remain unchanged.Get default values of a particular option: Use
faster("option_name", default = TRUE)
. Values will remain unchanged.Get default values of all options: Use
faster(default = TRUE)
. Values will remain unchanged.Set values of particular options: Use the form
faster(option 1 = value1, option2 = value2)
.Set all options to their defaults: Use
faster(restore = TRUE)
.
You cannot simultaneously get and set options.
To run most fasterRaster functions, you must set the grassDir
option.
Usage
faster(..., default = FALSE, restore = FALSE)
Arguments
... |
Either:
Options include:
|
default |
Logical: Return the default value(s) of the option(s). The default value of |
restore |
Logical: If |
Value
If options are changed, then a named list of option values before they were changed is returned invisibly.
If option values are requested, a named list with option values is returned (not invisibly).
Examples
if (grassStarted()) {
# See current values for options:
faster("grassDir")
faster("cores")
faster("memory")
faster("useDataTable")
faster() # all options
# See default values for options:
faster("cores", default = TRUE)
faster(default = TRUE) # all options
# Set options (change accordingly for your system!!!)
if (FALSE) {
opts. <- faster() # remember starting values of options
faster(grassDir = "C:/Program Files/GRASS GIS 8.4")
faster(verbose = TRUE, memory = 1024, cores = 1)
faster(c("grassDir", "verbose", "memory", "cores"))
faster(opts.) # reset options to starting values
}
}
Fill holes in a GVector
Description
fillHoles()
removes holes in a GVector
.
Usage
## S4 method for signature 'GVector'
fillHoles(x, fail = TRUE)
Arguments
x |
A |
fail |
Logical: If |
Value
A GVector
.
See Also
terra::fillHoles()
, GRASS manual page for tool v.fill.holes
(see grassHelp("v.fill.holes")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Fill NA cells in a raster using interpolation
Description
This function uses splines to fill NA
cells in a raster based on the values of nearby cells. Depending on the method used, not all NA
cells can be filled.
Usage
## S4 method for signature 'GRaster'
fillNAs(
x,
lambda = NULL,
method = "bilinear",
min = -Inf,
max = Inf,
cells = Inf
)
Arguments
x |
A |
lambda |
Either |
method |
Character: Type of spline, either " Note: The RST method will often display warnings, but these can be ignored. |
min , max |
Numeric: Lowest and highest values allowed in the interpolated values. Values outside these bounds will be truncated to the minimum/maximum value(s) allowed. The default imposes no constraints. For multi-layered rasters, you can supply a single value for |
cells |
Integer or numeric integer: Number of cells away from the non- |
Value
A GRaster
.
See Also
terra::interpNear()
, GRASS tool r.fillnulls
(see grassHelp("r.fillnulls")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster:
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
### Fill NAs:
bilinear <- fillNAs(elev)
bicubic <- fillNAs(elev, method = "bicubic")
rst <- fillNAs(elev, method = "rst")
maps <- c(elev, bilinear, bicubic, rst)
names(maps) <- c("original", "bilinear", "bicubic", "RST")
plot(maps)
### Constrain interpolated values to > 0
constrained <- fillNAs(elev, min = 0)
# Compare unconstrained and constrained:
minmax(bilinear)
minmax(constrained)
### Interpolate to only first 10 cells away from non-NA cells:
restrained <- fillNAs(elev, cells = 10)
maps <- c(elev, restrained)
names(maps) <- c("Original", "within 10 cells")
plot(maps)
}
Identify watershed basins and direction and accumulation of flow
Description
The flow()
function uses a raster representing elevation to compute other rasters representing:
Flow accumulation;
Direction of flow;
Watershed basins;
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 tool r.terraflow
] (see grassHelp("r.terraflow")
)
Usage
## S4 method for signature 'GRaster'
flow(
x,
direction = "multi",
return = "accumulation",
dirThreshold = Inf,
scratchDir = NULL
)
Arguments
x |
A |
direction |
Character: Either |
return |
Character vector: Indicates what rasters to return. Partial matching is used and case is ignored. Options include:
|
dirThreshold |
Numeric (default is |
scratchDir |
Character or |
Value
A GRaster
.
See Also
flowPath()
, streams()
, the GRASS tool r.terraflow
(see grassHelp("r.terraflow")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
elev <- fast(madElev)
# Calculate flow accumulation and watershed basins
water <- flow(elev, return = c("accum", "basins"))
water
elevWater <- c(elev, water)
plot(elevWater)
}
Path of water flow across a landscape
Description
This function finds the least-cost pathway from a set of starting points to the lowest cells accessible from them while, in each step, traversing "down" slope gradients. It is intended to depict the path a drop of water would take when flowing across a landscape. For a single starting point, the defaults settings will produce a raster with cells with values of 1 along the path. All other cells will be set to NA
.
Usage
## S4 method for signature 'GRaster'
flowPath(x, y, return = "ID")
Arguments
x |
A |
y |
A "points" |
return |
Character: Indicates the type of values "burned" into the cells of the output raster. Case is ignored and partial matching is used, but only one option can be selected.
|
Value
A GRaster
.
See Also
flow()
, streams()
, the GRASS tool r.drain
(see grassHelp("r.drain")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madCoast4 <- fastData("madCoast4")
# Convert to GRaster and crop to a sub-portion (easier for visualizing)
elev <- fast(madElev)
coast4 <- fast(madCoast4)
ant <- coast4[coast4$NAME_4 == "Antanambe"]
elevAnt <- crop(elev, ant)
# Create a set of random points to serve as starting points:
starts <- spatSample(elevAnt, 10, as.points = TRUE, seed = 2)
# Remove points in water:
starts <- starts[complete.cases(starts)]
# Calculate flow paths and label each by ID:
paths <- flowPath(elevAnt, starts)
paths
plot(elevAnt, legend = FALSE, main = "Flow path for each point")
plot(paths, add = TRUE)
plot(starts, pch = 1, add = TRUE)
# Flow paths with cell values indicating number of cells from each start:
seqs <- flowPath(elevAnt, starts, return = "seq")
plot(elevAnt, legend = FALSE, main = "Sequentially-numbered flow paths")
plot(seqs, add = TRUE)
plot(starts, pch = 1, add = TRUE)
# We can convert flow paths to lines:
seqLines <- as.lines(seqs)
plot(seqLines)
seqLines
}
Calculate cell values based on values of nearby cells
Description
This function calculates statistics on a moving "neighborhood" of cells of a raster. The neighborhood can be a square, circle, or a user-defined set of cells (with or without weights).
Usage
## S4 method for signature 'GRaster'
focal(x, w = 3, fun = "sum", circle = FALSE, quantile = 0.5)
Arguments
x |
A |
w |
Numeric integer or a square matrix with an odd number of rows and columns: The size and nature of the neighborhood:
|
fun |
Character: Name of the function to apply to the neighborhood:
The center cell value is always included in the calculations, and all calculations ignore |
circle |
Logical: If |
quantile |
Numeric between 0 and 1, inclusive: Quantile to calculate when |
Value
A GRaster
.
See Also
terra::focal()
, GRASS manual page for tool r.neighbors
(see grassHelp("r.neighbors")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Focal calculations:
sums <- focal(elev, fun = "sum")
means <- focal(elev, fun = "mean")
# Focal calculations on a circular window:
sds <- focal(elev, fun = "sd") # square
sdsCircle <- focal(elev, fun = "sd", circle = TRUE) # circle
sds
sdsCircle
plot(sds - sdsCircle)
# Focal calculations with user-defined weights:
w <- matrix(c(1, 0, 1, 0, 1, 0, 1, 0, 1), ncol = 3)
w
sumsWeighted <- focal(elev, fun = "sum", w = w)
s <- c(sums, sumsWeighted)
minmax(s)
}
Create fractal raster
Description
fractalRast()
creates a raster with a fractal pattern.
Usage
## S4 method for signature 'GRaster'
fractalRast(x, n = 1, mu = 0, sigma = 1, dimension = 2.05)
Arguments
x |
A |
n |
A numeric integer: Number of rasters to generate. |
mu , sigma |
Numeric: Mean and sample standard deviation of output. |
dimension |
Numeric: Fractal dimension. Must be between 2 and 3. |
Value
A GRaster
.
See Also
rSpatialDepRast()
, rNormRast()
, rUnifRast()
, rWalkRast()
, GRASS manual page for tool r.surf.fractal
(see grassHelp("r.surf.fractal")
)
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)
}
Landscape fragmentation class following Riitters et al. (2020)
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 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 isNA
).1: Patch
2: Transitional
3: Perforated
4: Edge
5: Undetermined (not possible to obtain when
w = 3
)6: Interior
Usage
## S4 method for signature 'SpatRaster'
fragmentation(
x,
w = 3,
undet = "undetermined",
none = NA,
na.rm = TRUE,
cores = faster("cores"),
verbose = TRUE
)
## S4 method for signature 'GRaster'
fragmentation(x, w = 3, undet = "undetermined", none = NA, verbose = TRUE)
Arguments
x |
A |
w |
An odd, positive integer: Size of the window across which fragmentation is calculated (in units of "rows" and "columns"). The default is 3, meaning the function uses a 3x3 moving window to calculate fragmentation. For large rasters, compute time is ~O( |
undet |
Character: How to assign the "undetermined" case. Valid values are |
none |
Integer or |
na.rm |
Logical: If |
cores |
Integer: Number of processor cores to use for when processing a |
verbose |
Logical: If |
Value
A categorical SpatRaster
or GRaster
. The values assigned to each class can be seen with levels()
.
References
Riitters, K., J. Wickham, R. O'Neill, B. Jones, and E. Smith. 2000. Global-scale patterns of forest fragmentation. Conservation Ecology 4:3. URL: http://www.consecol.org/vol4/iss2/art3/. Also note the errata.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data:
madForest <- fastData("madForest2000") # raster
### Fragmentation classes from a SpatRaster
fragTerra <- fragmentation(madForest)
plot(fragTerra)
levels(fragTerra)
freq(fragTerra)
### Fragmentation classes from a GRaster
# Convert to GRaster:
forest <- fast(madForest)
# Fragmentation class:
frag <- fragmentation(forest)
plot(frag)
levels(frag)
freq(frag)
}
Frequencies of cell values in a raster
Description
freq()
tabulates the frequency of cell values in a raster. For rasters where datatype()
is integer
or factor
, the frequency of each value or level is reported. For other rasters, the range of values is divided into bins, and the number of cells with values in each bin is reported.
Usage
## S4 method for signature 'GRaster'
freq(x, digits = 3, bins = 100, value = NULL)
Arguments
x |
A |
digits |
Numeric integer: Number of digits by which to round raster values. Ignored for integer and categorical rasters. |
bins |
Positive numeric integer: Number of bins in which to divide values of |
value |
Numeric or |
Value
A data.frame
or a named list
of data.frame
s, one per layer in x
.
See Also
terra::freq()
, tool r.stats
in GRASS
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev") # raster
madCover <- fastData("madCover") # categorical raster
# Convert to GRasters
elev <- fast(madElev) # raster
cover <- fast(madCover) # categorical raster
# Frequencies of integer raster values
f <- freq(elev)
print(f) # have to do this sometimes if output is a data table
# Frequencies of categorical raster values
f <- freq(cover)
print(f) # have to do this sometimes if output is a data table
# Frequencies of given values
f <- freq(elev, value = 1)
print(f) # have to do this sometimes if output is a data table
# When a GRaster has non-integer values, they will be binned:
f <- freq(elev + 0.1, bins = 10)
print(f)
}
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 tool r.geomorphon
using grassHelp("r.geomorphon")
for more details and diagrams of each type of geomorphon. Geomorphon types include:
Flat areas: Focal area has approximately the same elevation as surrounding areas
Pits: An area is lower than all other surrounding areas
Valley: Focal area has elevation similar to two opposing side of the window but lower than the other two opposing sides
Footslope: Focal region is at the "bottom" of a slope
Hollow: A small valley/indention in the crest of a hill
Slope: Cells in the window form an approximately uniform slope
Spur: An extrusion at the foot of a hill (i.e.,, a small hill extending out from the foot of a slope)
Shoulder: The crest of a slope
Ridge: Opposite of a valley; focal area is higher than two opposing sides but approximately the same elevation as the other two opposing sides
Peak: Focal area is higher than any other in the window
Usage
## S4 method for signature 'GRaster'
geomorphons(
x,
inner = 0,
outer = 3,
unit = "cells",
flat = 1,
flatDist = 0,
mode = "1"
)
Arguments
x |
A single-layer |
inner , outer |
Integer: Inner and outer radii of the torus used to identify geomorphons, in cells or meters (set by argument |
unit |
Character: Units of |
flat |
Numeric value >= 0: Minimum difference (in degrees) between the focal area areas around it for a geomorphon to be considered as "flat". Larger cells (i.e., ~1 km resolution or larger) require smaller values (<<1) to correctly identify flat areas. Higher values result in more areas being classified as "flat" geomorphons. The default value is 1. |
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 |
mode |
Character: Method for implementing the zenith/line-of-site search. Partial matching is used:
|
Value
A categorical GRaster
where each geomorphon is a category (see vignette("GRasters", package = "fasterRaster")
).
See Also
GRASS manual for tool r.geomorphon
(see grassHelp("r.geomorphon")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Geomorphons:
geos <- geomorphons(elev)
geos
levels(geos) # levels
freq(geos) # frequencies across cells
col <- c("gray90", "red", "orange", "blue", "green", "pink", "firebrick",
"purple", "gray50", "black")
plot(geos, col = col)
}
Geometry of a GVector (points, lines, or polygons)
Description
geomtype()
reports whether a GVector
represents points, lines, or polygons. The "is.*
" functions test whether the GVector
represents points, lines, or polygons.
Usage
## S4 method for signature 'GVector'
geomtype(x, grass = FALSE)
## S4 method for signature 'GVector'
is.points(x)
## S4 method for signature 'GVector'
is.lines(x)
## S4 method for signature 'GVector'
is.polygons(x)
Arguments
x |
A |
grass |
Logical: If |
Value
geomtype()
returns either "points", "lines", or "polygons" if the grass
arguments is FALSE
, or "point", "line", "area" if grass
is TRUE
. The "is.*
" functions return TRUE
or FALSE
.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Summary statistics for GRasters
Description
global()
calculates a summary statistic across all the cells of a GRaster
. It returns a single value for each layer of the raster.
Usage
## S4 method for signature 'GRaster'
global(x, fun = "mean", probs = seq(0, 1, 0.25), ...)
## S4 method for signature 'missing'
global(x, ...)
Arguments
x |
A |
fun |
Character vector: The name of the function(s):
|
probs |
Numeric within the range from 0 to 1: Quantile(s) at which to calculate |
... |
Other arguments (unused). |
Value
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.
See Also
terra::global()
and GRASS tool r.univar
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# What functions can we use with global()?
global()
# Calculate global statistics:
global(elev, fun = c("mean", "var", "varpop"))
global(elev, "quantile", probs = c(0.25, 0.5, 0.75))
global(elev, "*") # calculate all available functions
}
Start the GRASS GUI (potentially dangerous!)
Description
This function starts the GRASS GUI. It is provided merely as a utility... in most cases, it should not be used if you are doing any kind of analysis of rasters or vectors using fasterRaster. The reason for this prohibition is that fasterRaster objects, like GRaster
s and GVector
s, are really "pointers" to objects in GRASS. If fasterRaster points to a GRASS object that is changed in GRASS but not R, then fasterRaster will not "know" about it, so changed won't be reflected in the fasterRaster object.
One aspect of the GUI that is useful but will not change objects is to use it to plot rasters and vectors. However, the a fasterRaster object in R will have a different name in GRASS. The name in GRASS of a GVector
or GRaster
is given by sources()
.
Usage
## S4 method for signature 'missing'
grassGUI()
Value
Nothing (starts the GRASS GUI).
See Also
Examples
if (grassStarted()) {
# DANGER: Making changes to rasters/vectors in the GUI can "break" them in R.
if (interactive()) grassGUI()
}
Open the help page for a GRASS tool
Description
This function opens the manual page for a GRASS tool (function) in your browser.
Usage
grassHelp(x, online = FALSE)
Arguments
x |
Character: Any of:
|
online |
Logical: If |
Value
Nothing (opens a web page).
Examples
if (grassStarted() & interactive()) {
# Open help pages for `r.mapcalc` and `r.sun`:
grassHelp("r.mapcalc")
grassHelp("r.sun")
# GRASS table of contents:
grassHelp("toc")
# Index page:
grassHelp("index")
}
GRASS citation, version, and copyright information
Description
Report the GRASS citation, version/release year, version number, or copyright information.
Usage
grassInfo(x = "citation")
Arguments
x |
Character: What to return. Any of:
Partial matching is used and case is ignored. |
Value
Character.
Examples
if (grassStarted()) {
# Citation
grassInfo()
# Version number
grassInfo("version")
# Version number
grassInfo("versionNumber")
# Version number
grassInfo("versionNumber")
# Copyright
grassInfo("copyright")
}
Has "GRASS" been started or not?
Description
Returns TRUE
or FALSE
, depending on whether a GRASS connection has been made or not within the current R session. Usually used only by developers. GRASS is started the first time fast()
is used.
Usage
grassStarted()
Value
Logical.
Examples
grassStarted()
Create a grid GVector
Description
This function creates a GVector
of "wall-to-wall" cells (like a lattice). The input can be a GVector
or GRaster
, which provides the extent of the output.
Usage
## S4 method for signature 'GRaster'
grid(x, nx = NULL, ny = NULL, use = "number", angle = 0)
## S4 method for signature 'GVector'
grid(x, nx = NULL, ny = NULL, use = "number", angle = 0)
Arguments
x |
A |
nx , ny |
Integer or numeric:
|
use |
Character: How to generate the grid. If this is |
angle |
Numeric: Degrees by which to rotate grid (from north, clockwise). |
Value
A GVector
.
See Also
hexagons()
, tool v.mkgrid
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
# Points vector of specimens of species in the plant genus Dypsis
madCoast0 <- fastData("madCoast0")
# Convert sf to a GVector:
coast <- fast(madCoast0)
### grid
# grid specified by number of cells in x-dimension
g1 <- grid(coast, nx = 10)
plot(coast, col = "cornflowerblue")
plot(g1, add = TRUE)
# grid specified by number of cells in x- and y-dimension
g2 <- grid(coast, nx = 10, ny = 5)
plot(coast, col = "cornflowerblue")
plot(g2, add = TRUE)
# grid specified by size of cells in both dimensions
g3 <- grid(coast, nx = 1250, ny = 2000, use = "size")
plot(coast, col = "cornflowerblue")
plot(g3, add = TRUE)
### hexagons
hexes <- hexagons(coast, ny = 10)
plot(hexes)
plot(coast, lwd = 2, add = TRUE)
hexes <- hexagons(coast, ny = 10, expand = c(0.3, 0.1))
plot(hexes)
plot(coast, lwd = 2, add = TRUE)
}
Return first or last part of the data frame of a GVector
Description
Return the first or last part of a GVector
's data table.
Usage
## S4 method for signature 'GVector'
head(x, n = 6L, keepnums = TRUE, ...)
## S4 method for signature 'GVector'
tail(x, n = 6L, keepnums = TRUE, ...)
Arguments
x |
A |
n |
Integer: Number of rows to display. |
keepnums |
Logical: If no |
... |
Other arguments. |
Value
A data.table
or data.frame
.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Create a hexagonal grid
Description
This function creates a GVector
of "wall-to-wall" hexagons. The input can be a GVector
or GRaster
, which provides the extent of the output.
Usage
## S4 method for signature 'GRaster'
hexagons(x, ny = 10, expand = 0, angle = 0)
## S4 method for signature 'GVector'
hexagons(x, ny = 10, expand = 0, angle = 0)
Arguments
x |
A |
ny |
Integer or numeric integer: Number of rows of hexagons that span the extent of object |
expand |
One or two numeric values: Expand the region by this proportion in both directions (a single value) or in the x- and y-dimensions separately. Expanding the region can be helpful to ensure the entire area of interest is covered by polygons, which can otherwise leave gaps at the edges. The number of rows and columns will be increased, but the number of hexagons that span |
angle |
Numeric: Degrees by which to rotate grid (from north, clockwise). |
Value
A GVector
.
See Also
grid()
, tool v.mkgrid
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
# Points vector of specimens of species in the plant genus Dypsis
madCoast0 <- fastData("madCoast0")
# Convert sf to a GVector:
coast <- fast(madCoast0)
### grid
# grid specified by number of cells in x-dimension
g1 <- grid(coast, nx = 10)
plot(coast, col = "cornflowerblue")
plot(g1, add = TRUE)
# grid specified by number of cells in x- and y-dimension
g2 <- grid(coast, nx = 10, ny = 5)
plot(coast, col = "cornflowerblue")
plot(g2, add = TRUE)
# grid specified by size of cells in both dimensions
g3 <- grid(coast, nx = 1250, ny = 2000, use = "size")
plot(coast, col = "cornflowerblue")
plot(g3, add = TRUE)
### hexagons
hexes <- hexagons(coast, ny = 10)
plot(hexes)
plot(coast, lwd = 2, add = TRUE)
hexes <- hexagons(coast, ny = 10, expand = c(0.3, 0.1))
plot(hexes)
plot(coast, lwd = 2, add = TRUE)
}
Hillshading
Description
Hillshade rasters are often used for display purposes because they make topographical relief look "real" to the eye.
Usage
## S4 method for signature 'GRaster'
hillshade(x, angle = 45, direction = 0, zscale = 1)
Arguments
x |
A |
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). |
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 |
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. |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
# Calculate all topographic metrics
topos <- terrain(elev, v = "*")
topos
plot(topos) # NB Aspect has values of NA when it cannot be defined
# Calculate a hillshade raster
hs <- hillshade(elev)
plot(hs)
}
Plot a histogram of raster values
Description
This function creates a histogram of values in GRaster
. The function is modeled after graphics::hist()
, but actually uses graphics::barplot()
.
Usage
## S4 method for signature 'GRaster'
hist(x, layer, maxnl = 16, bins = 30, freq = TRUE, ...)
Arguments
x |
A |
layer |
Character, numeric, or integer: Indicates which layer of a multi-layer |
maxnl |
Maximum number of layers for which to create histograms. This is 16 by default, but ignored if |
bins |
Positive numeric integer: Number of bins in which to divide values of a raster with continuous values. For |
freq |
Logical: If |
... |
Arguments to pass to |
Value
A named list of data.frame
s (invisibly), one per layer plotted, and creates a graph.
Examples
if (grassStarted()) {
# Example data
madElev <- fastData("madElev") # elevation raster
madLANDSAT <- fastData("madLANDSAT") # multi-layer raster
madRivers <- fastData("madRivers") # lines vector
# Convert SpatRaster to GRaster and SpatVector to GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
landsat <- fast(madLANDSAT)
# Plot:
plot(elev)
plot(rivers, add = TRUE)
# Histograms:
hist(elev)
hist(landsat)
# Plot surface reflectance in RGB:
plotRGB(landsat, 3, 2, 1) # "natural" color
plotRGB(landsat, 4, 1, 2, stretch = "lin") # emphasize near-infrared (vegetation)
# Make composite map from RGB layers and plot in grayscale:
comp <- compositeRGB(r = landsat[[3]], g = landsat[[2]], b = landsat[[1]])
grays <- paste0("gray", 0:100)
plot(comp, col = grays)
}
Horizon height
Description
horizonHeight()
uses a raster representing elevation to calculate the height of the horizon in a particular direction from each cell on a raster. Height is expressed in radians or degrees from the horizontal.
Usage
## S4 method for signature 'GRaster'
horizonHeight(
x,
units = "radians",
step = 90,
northIs0 = TRUE,
bufferZone = 0,
distance = 1,
maxDist = NULL
)
Arguments
x |
A |
units |
Character: Units of the height. Either |
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. |
northIs0 |
Logical: If |
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). |
distance |
Numeric between 0.5 and 1.5, inclusive (default is 1): This determines the step size when searching for the horizon from a given point. The default value of 1 goes cell-by-cell (i.e., search distance step size is one cell width). |
maxDist |
Either |
Value
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.
See Also
GRASS manual page for tool r.horizon
(see grassHelp("r.horizon")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# convert a SpatRaster to a GRaster
elev <- fast(madElev)
# calculate horizon height in north and east directions
hhNorth <- horizonHeight(elev)
hhNorth
plot(hhNorth)
# calculate horizon height in east and north directions
hhEast <- horizonHeight(elev, northIs0 = FALSE)
hhEast
plot(hhEast)
}
GRaster with values equal to row, column, coordinate, regular, or "chess"
Description
This function can be used to make a GRaster
with cell values equal to the cell center's longitude, latitude, row, or column, or in a "chess"-like or "regular" pattern.
Usage
## S4 method for signature 'GRaster'
init(x, fun, odd = TRUE, vals = c(0, 1))
Arguments
x |
A |
fun |
Character: Any of:
|
odd |
Logical: If |
vals |
Vector of two numeric values: If |
Value
A GRaster
with as many layers as x
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster, rivers vector
madElev <- fastData("madElev")
# Convert to a GRaster
elev <- fast(madElev)
# Cell coordinates
init(elev, "x")
init(elev, "y")
# Cell row or column
init(elev, "row")
init(elev, "col")
# Chess
elevAgg <- aggregate(elev, 32) # make cells bigger so we can see them
chessOdd <- init(elevAgg, "chess")
chessEven <- init(elevAgg, "chess", odd = FALSE)
chess <- c(chessOdd, chessEven)
names(chess) <- c("odd", "even")
plot(chess)
# Chess with user-defined values
elevAgg <- aggregate(elev, 32) # make cells bigger so we can see
chessOdd13 <- init(elevAgg, "chess", vals = c(0, 13))
chessEven13 <- init(elevAgg, "chess", odd = FALSE, vals = c(0, 13))
chess13 <- c(chessOdd13, chessEven13)
names(chess13) <- c("odd", "even")
plot(chess13)
# Regular
elevAgg <- aggregate(elev, 32) # make cells bigger so we can see
regOdd <- init(elevAgg, "regular")
regEven <- init(elevAgg, "regular", odd = FALSE)
reg <- c(regOdd, regEven)
names(reg) <- c("odd", "even")
plot(reg)
}
Interpolate values at points to a GRaster using inverse-distance weighting
Description
This function interpolates values from a set of points to a raster using inverse distance weighting (IDW).
Usage
## S4 method for signature 'GVector,GRaster'
interpIDW(x, y, field, nPoints = Inf, power = 2)
Arguments
x |
A "points" |
y |
A |
field |
Character, integer, or numeric integer: Name or index of the column in |
nPoints |
Integer or numeric integer: Number of nearest points to use for interpolation. The default is to use all points ( |
power |
Numeric value > 0: Power to which to take distance when interpolating. The default value is two, so the value of each point used for interpolation is |
Value
A GRaster
.
See Also
terra::interpIDW()
, interpSplines()
, fillNAs()
, GRASS tool v.surf.idw
(se grassHelp("v.surf.idw")
)
Interpolate values at points to a GRaster using splines
Description
This function interpolates values in the data table of a "points" GVector
to a GRaster
using splines with Tykhonov regularization to avoid overfitting.
Usage
## S4 method for signature 'GVector,GRaster'
interpSplines(
x,
y,
field,
method = "bilinear",
lambda = NULL,
solver = "Cholesky",
xlength = NULL,
ylength = NULL,
interpolate = TRUE,
verbose = is.null(lambda)
)
Arguments
x |
A "points" |
y |
A |
field |
Character or integer or numeric integer: Name or index of the column in |
method |
Character: The method to use for interpolation can be either |
lambda |
Either |
solver |
Character: Type of solver to use. Can be either of |
xlength , ylength |
Either |
interpolate |
Logical: If |
verbose |
Logical: if |
Details
If you receive the error, "No data within this subregion. Consider increasing spline step values, try increasing the values of xlength
and ylength
.
If cross-validation takes too long, or other warnings/errors persist, you can randomly subsample x
to ~100 points to get an optimum value of lambda
(using interpolate = FALSE
), then use this value in the same function again without cross-validation (setting lambda
equal to this value and interpolate = TRUE
).
Value
Output depends on values of lambda
and interpolate
:
-
lambda
isNULL
andinterpolate
isTRUE
: AGRaster
with an attribute namedlambdas
. This is adata.frame
with values oflambda
that were assessed, plusmean
(mean residual value) andrms
(root mean square error). You can see the table usingattr(output_raster, "lambdas", exact = TRUE)
. -
lambda
isNULL
andinterpolate
isFALSE
: Adata.frame
with values oflambdas
that were assessed, plusmean
(mean residual value) andrms
(root mean square error). You can see the table usingattr(output_raster, "lambdas", exact = TRUE)
. -
lambda
is a number (interpolate
is ignored): AGRaster
.
See Also
interpIDW()
, fillNAs()
, GRASS tool v.surf.bspline
(see grassHelp("v.surf.bspline")
)
Intersection of two GVectors
Description
The intersect()
function selects the area of overlap between two GVector
s of the same type (points, lines or polygons). You can also use the *
operator (e.g., vect1 * vect2
).
Usage
## S4 method for signature 'GVector,GVector'
intersect(x, y)
Arguments
x , y |
|
Value
A GVector
.
See Also
c()
, aggregate()
, crop()
, union()
, xor()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Polygon of coastal Madagascar and Dypsis specimens
madCoast4 <- fastData("madCoast4") # polygons
madDypsis <- fastData("madDypsis") # points
# Convert vectors:
coast4 <- fast(madCoast4)
dypsis <- fast(madDypsis)
# Create another polygons vector from a convex hull around Dypsis points
hull <- convHull(dypsis)
### union()
unioned <- union(coast4, hull)
plot(unioned)
plus <- coast4 + hull # same as union()
### intersect
inter <- intersect(coast4, hull)
plot(coast4)
plot(hull, border = "red", add = TRUE)
plot(inter, border = "blue", add = TRUE)
### xor
xr <- xor(coast4, hull)
plot(coast4)
plot(xr, border = "blue", add = TRUE)
### erase
erased <- erase(coast4, hull)
plot(coast4)
plot(erased, border = "blue", add = TRUE)
minus <- coast4 - hull # same as erase()
}
Test if a GRaster or GVector is 2- or 3-dimensional
Description
Test whether a GRaster
or GVector
is 2- or 3-dimensional.
Usage
## S4 method for signature 'GSpatial'
is.2d(x)
## S4 method for signature 'GSpatial'
is.3d(x)
Arguments
x |
An object that inherits from the |
Value
Logical.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Data type of a raster
Description
In fasterRaster, rasters can have three data types: "factor" (categorical rasters), "integer" (integers), "float" (floating point values, accurate to the 6th to 9th decimal places), and "double" (double-precision values, accurate to the 15th to 17th decimal places). The type of raster can be checked with:
-
is.factor()
: The raster will have integer values and categories matched to the integers (see levels()). -
is.int()
: Are values integers? Note thatis.int()
will returnFALSE
for categorical rasters, even though cell values are technically integers. -
is.cell()
: Are values integers (TRUE
forinteger
and categorical rasters). -
is.float()
: Are values floating-point precision? -
is.doub()
: Are values double-floating point precision?
Usage
## S4 method for signature 'GRaster'
is.int(x)
## S4 method for signature 'GRaster'
is.cell(x)
## S4 method for signature 'GRaster'
is.float(x)
## S4 method for signature 'GRaster'
is.doub(x)
## S4 method for signature 'GRaster'
is.factor(x)
Arguments
x |
A |
Value
Logical.
See Also
datatype()
, terra::datatype()
, as.int()
, as.float()
, as.doub()
, is.factor()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Test if a coordinate reference system is unprojected
Description
is.lonlat()
attempts to determine if a coordinate reference system is unprojected (e.g., WGS84, NAD83, NAD27, etc.). For GRaster
s and GVector
s, the function should always be correct. For WKT character strings and sf
vectors, it does this by looking for the "CONVERSION[" tag in the WKT string (or the object's WKT string), and if it finds one, returns FALSE
. This may not be truthful in all cases.
Usage
## S4 method for signature 'character'
is.lonlat(x)
## S4 method for signature 'GLocation'
is.lonlat(x)
## S4 method for signature 'sf'
is.lonlat(x)
Arguments
x |
A WKT coordinate reference string or an object from which on can be obtained (e.g., a |
Value
Logical (TRUE
if unprojected, FALSE
otherwise).
See Also
Mathematical operations on each layer of a GRasters
Description
You can apply mathematical functions to each layer of a GRaster
. The output is a GRaster
with the same number or layers as the input. Available functions include:
-
NA
s:-
is.na()
-
not.na()
-
Absolute value:
abs()
Trigonometric functions (assumes values are in radians):
-
cos()
-
sin()
-
tan()
-
acos()
-
asin()
-
atan()
-
atan2()
-
Exponential and logarithmic functions:
-
exp()
-
log()
(natural log) -
ln()
(also natural log) -
log2()
(log, base 2) -
log10()
(log, base 10) -
log1p()
(same aslog(x + 1)
) -
log10p()
(same aslog(x + 1, base = 10)
)
-
Power functions:
-
sqrt()
-
x^y
-
Rounding:
-
round()
-
floor()
(round down) -
ceiling()
(round up) -
trunc()
(remove decimal portion)
-
Usage
## S4 method for signature 'GRaster'
is.na(x)
## S4 method for signature 'GRaster'
not.na(x, falseNA = FALSE)
## S4 method for signature 'GRaster'
abs(x)
## S4 method for signature 'GRaster'
sin(x)
## S4 method for signature 'GRaster'
cos(x)
## S4 method for signature 'GRaster'
tan(x)
## S4 method for signature 'GRaster'
asin(x)
## S4 method for signature 'GRaster'
acos(x)
## S4 method for signature 'GRaster'
atan(x)
## S4 method for signature 'GRaster,GRaster'
atan2(y, x)
## S4 method for signature 'GRaster'
exp(x)
## S4 method for signature 'GRaster'
log1p(x)
## S4 method for signature 'GRaster'
log10p(x)
## S4 method for signature 'GRaster'
log(x, base = exp(1))
## S4 method for signature 'GRaster'
ln(x)
## S4 method for signature 'GRaster'
log2(x)
## S4 method for signature 'GRaster'
log10(x)
## S4 method for signature 'GRaster'
sqrt(x)
## S4 method for signature 'GRaster'
round(x, digits = 0)
## S4 method for signature 'GRaster'
floor(x)
## S4 method for signature 'GRaster'
ceiling(x)
## S4 method for signature 'GRaster'
trunc(x)
Arguments
x , y |
|
falseNA |
Logical (function |
base |
Numeric: Base of the logarithm. |
digits |
Numeric: Number of digits to round to. If negative, then rounding is to the nearest positive power of 10. For example, if |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
elevs <- c(elev, elev, log10(elev) - 1, sqrt(elev))
names(elevs) <- c("elev1", "elev2", "log_elev", "sqrt_elev")
elev
elevs
# do some math
elev + 100
elev - 100
elev * 100
elev / 100
elev ^ 2
elev %/% 100 # divide then round down
elev %% 100 # modulus
100 + elev
100 %/% elev
100 %% elev
elevs + 100
100 + elevs
# math with logicals
elev + TRUE
elev - TRUE
elev * TRUE
elev / TRUE
elev ^ TRUE
elev %/% TRUE # divide then round down
elev %% TRUE # modulus
elevs + TRUE
TRUE + elevs
# Raster interacting with raster(s):
elev + elev
elev - elev
elev * elev
elev / elev
elev ^ log(elev)
elev %/% sqrt(elev) # divide then round down
elev %% sqrt(elev) # modulus
elevs + elev
elev * elevs
# sign
abs(-1 * elev)
abs(elevs)
# powers
sqrt(elevs)
# trigonometry
sin(elev)
cos(elev)
tan(elev)
asin(elev)
acos(elev)
atan(elev)
atan(elevs)
atan2(elev, elev^1.2)
atan2(elevs, elev^1.2)
atan2(elev, elevs^1.2)
atan2(elevs, elevs^1.2)
# logarithms
exp(elev)
log(elev)
ln(elev)
log2(elev)
log1p(elev)
log10(elev)
log10p(elev)
log(elev, 3)
log(elevs)
# rounding
round(elev + 0.5)
floor(elev + 0.5)
ceiling(elev + 0.5)
trunc(elev + 0.5)
}
Kernel density estimator of points
Description
kernel()
creates a raster using a kernel density estimator of the density of points in a "points" GVector
.
Usage
## S4 method for signature 'GVector'
kernel(x, y, kernel = "Epanechnikov", optimize = TRUE, h = NULL)
Arguments
x |
A "points" |
y |
A |
kernel |
Character: Name of the kernel function to use. Possible values include:
Partial matching is used, and case is ignored. |
optimize |
Logical: If |
h |
Numeric or If this is
If the Gaussian kernel is used, and Otherwise, if |
Value
A GRaster
.
See Also
GRASS manual page for tool v.kernel
(see grassHelp("v.kernel")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster, plant specimen collections, rivers vector,
# outline of area vector
madElev <- fastData("madElev")
madDypsis <- fastData("madDypsis")
# Convert to fasterRaster format:
elev <- fast(madElev)
dypsis <- fast(madDypsis)
# Kernel density estimation:
kde <- kernel(dypsis, elev)
plot(kde)
plot(dypsis, add = TRUE, pch = 1)
}
Correlation between GRasters
Description
This function returns a correlation or covariance matrix between two or more GRaster
layers. This function returns the sample correlation and covariance (i.e., the denominator is n - 1).
Usage
## S4 method for signature 'GRaster'
layerCor(x, fun = "cor")
Arguments
x |
A |
fun |
Character: Name of the statistic to calculate; either |
Value
A numeric matrix
.
See Also
terra::layerCor()
, stats::cor()
, stats::cov()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster:
chelsa <- fast(madChelsa)
# Correlation
layerCor(chelsa, "cor")
# Covariance
layerCor(chelsa, "cov")
}
Set and get categories for categorical rasters
Description
GRaster
s can represent categorical data. Cell values are actually integers, each corresponding to a category, such as "desert" or "wetland." A categorical raster is associated with a table that matches each value to a category name. The table must be NULL
(i.e., no categories–so not a categorical raster), or have at least two columns. The first column must have integers and represent raster values. One or more subsequent columns must have category labels. The column with these labels is the "active category".
-
levels()
: Displays the "levels" table of a raster (just the value and active category columns). -
cats()
: Displays the entire "levels" table of a raster. -
levels()<-
: (Re)assigns the "levels" table to each layer of a raster. Assigning a "levels" table to an integer raster makes it a categorical raster. -
categories()
: (Re)assigns the "levels" table to specific layer(s) of a raster. For a complete list of functions relevant to categorical rasters, see 'vignette("GRasters", package = "fasterRaster")).
Usage
## S4 method for signature 'GRaster'
levels(x)
## S4 method for signature 'GRaster'
cats(x, layer = 1:nlyr(x))
## S4 method for signature 'GRaster'
categories(x, layer = 1, value, active = 1)
## S4 replacement method for signature 'GRaster,data.frame'
levels(x) <- value
## S4 replacement method for signature 'GRaster,data.table'
levels(x) <- value
## S4 replacement method for signature 'GRaster,GRaster'
levels(x) <- value
## S4 replacement method for signature 'GRaster,list'
levels(x) <- value
Arguments
x |
A |
layer |
Numeric integers, logical vector, or character: For |
value |
A |
active |
An integer or a character: The index or column name of the column used for category labels (the "active column"). Following |
Value
Values returned are:
-
levels()
andcats()
: A list ofdata.frame
s ordata.table
s, one per raster layer. -
levels()<-
andcategories()
: AGRaster
.
See Also
terra::levels()
, levels<-
, terra::cats()
, terra::categories()
, see vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Create longitude/latitude rasters
Description
longlat()
creates two rasters, one with cell values equal to the longitude of the cell centers, and one with cell values equal to the latitude of the cell centers.
Usage
## S4 method for signature 'GRaster'
longlat(x, degrees = TRUE)
Arguments
x |
A |
degrees |
Logical: If |
Value
A GRaster
stack.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
# Create longitude/latitude rasters
ll <- longlat(elev)
ll # note units of cell values!
}
Rasters of bioclimatic variables for an eastern portion of Madagascar
Description
Rasters of bioclimatic variables for an eastern portion of Madagascar from CHELSA version 2.1 in unprojected (WGS84) coordinates. Values represent averages across 1980-2010. Only these BIOCLIM variables are included:
* bio1
: Mean annual temperature (deg C)
* bio7
: Temperature annual range (hottest - coldest month temperature; deg C)
* bio12
: Total annual precipitation (mm)
* bio15
: Precipitation seasonality (unit-less)
Format
An object of class SpatRaster
in unprojected (WGS84) coordinates.
Source
References
Karger, D.N., Conrad, O., Bohner, J., Kawohl, T., Kreft, H., Soria-Auza, R.W., Zimmermann, N.E., Linder, H.P., and Kessler, M. 2017. Climatologies at high resolution for the earth's land surface areas. Scientific Data 4:170122. doi:10.1038/sdata.2017.122
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Shapefile of a portion of the coastline of Madagascar
Description
Borders of a selected portion of Madagascar
Format
ESRI Shapefile.
Source
Database of Global Administrative Areas Version 2.8 (GADM)
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Spatial vector of a portion of the coastline of Madagascar
Description
Borders of a selected portion of Madagascar
Usage
data(madCoast4)
Format
An object of class sf
.
Source
Database of Global Administrative Areas Version 2.8 (GADM)
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Spatial vector of a portion of the coastline of Madagascar
Description
Borders of a selected portion of Madagascar
Usage
data(madCoast4)
Format
An object of class sf
.
Source
Database of Global Administrative Areas Version 2.8 (GADM)
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Raster of land cover for an eastern portion of Madagascar
Description
Raster of land cover for an eastern portion of Madagascar. Note that the land cover classes have been simplified, so this raster should not be used for "real" analyses.
Format
An object of class SpatRaster
in unprojected (WGS84) coordinates.
Source
References
Arino O., P. Bicheron, F. Achard, J. Latham, R. Witt and J.-L. Weber. 2008. GlobCover: The most detailed portrait of Earth. European Space Agency Bulletin 136:25-31. http://due.esrin.esa.int.
See Also
madCoverCats, vignette("GRasters", package = "fasterRaster")
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Table of land cover classes for an eastern portion of Madagascar
Description
This data frame corresponds to the madCover raster, which represents land cover for an eastern portion of Madagascar. Note that the land cover classes have been simplified, so this table and raster should not be used for "real" analyses.
Format
An object of class data.frame
.
Source
References
Arino O., P. Bicheron, F. Achard, J. Latham, R. Witt and J.-L. Weber. 2008. GlobCover: The most detailed portrait of Earth. European Space Agency Bulletin 136:25-31. http://due.esrin.esa.int.
See Also
madCover, vignette("GRasters", package = "fasterRaster")
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Spatial points vector of records of Dypsis in eastern Madagascar
Description
Spatial points vector of herbarium specimens and observations of plants in the genus Dypsis (slender, evergreen palms) from a portion of eastern Madagascar.
Usage
data(madDypsis)
Format
An object of class sf
.
Source
Global Biodiversity Information Facility (GBIF)
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Elevation raster for an eastern portion of Madagascar
Description
Elevation raster for an eastern portion of Madagascar.
Format
An object of class SpatRaster
. Values are mean meters above sea level.
Source
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Forest cover in year 2000 for a portion of Madagascar
Description
Raster of occurrence/non-occurrence of forest cover in a portion of Madagascar. Cells are 30-m in resolution. Values represent forest (1) or non-forest (NA
).
Format
An object of class SpatRaster
.
References
Vielledent, G., Grinand, C., Rakotomala, F.A., Ranaivosoa, R., Rakotoarijaona, J-R., Allnutt, T.F., and Achard, F. 2018. Combining global tree cover loss data with historical national forest cover maps to look at six decades of deforestation and forest fragmentation in Madagascar. Biological Conservation 222:189-197. doi:10.1016/j.biocon.2018.04.008.
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Forest cover in year 2014 for a portion of Madagascar
Description
Raster of occurrence/non-occurrence of forest cover in a portion of Madagascar. Cells are 30-m in resolution. Values represent forest (1) or non-forest (NA
).
Format
An object of class SpatRaster
..
References
Vielledent, G., Grinand, C., Rakotomala, F.A., Ranaivosoa, R., Rakotoarijaona, J-R., Allnutt, T.F., and Achard, F. 2018. Combining global tree cover loss data with historical national forest cover maps to look at six decades of deforestation and forest fragmentation in Madagascar. Biological Conservation 222:189-197. doi:10.1016/j.biocon.2018.04.008.
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Rasters of surface reflectance for an eastern portion of Madagascar
Description
Raster layers of surface reflectance from LANDSAT 9 for an eastern portion of Madagascar taken May 21, 2023. Four bands are represented:
‘band2’: Blue (450-510 nm)
‘band3’: Green (530-590 nm)
‘band4’: Red (640-670 nm)
‘band5’: Near-infrared (850-880 nm) The rasters have been resampled to 90-m resolution to reduce their size, then rescaled to integers in the range 0 to 255.
Format
An object of class SpatRaster
in Universal Trans-Mercator (UTM), Zone 39 North with a WGS84 coordinate system, at 90 m resolution.
Source
United States Geological Survey's EarthExplorer. Also see band definitions.
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Rasters of average monthly precipitation for an eastern portion of Madagascar
Description
Rasters of precipitation for an eastern portion of Madagascar from WorldClim 2.1 at ~3.33 arcminute resolution projected to the Tananarive (Paris)/Laborde Grid coordinate reference system. Values represent monthly averages across 1970-2000. Units are in millimeters. These should not be used for formal analysis.
Format
An object of class SpatRaster
.
Source
References
Fick, S.E. and Hijmans, R.J. 2017. WorldClim 2: New 1-km spatial resolution climate surfaces for global land areas. International Journal of Climatology 37:4302-4315. doi:10.1002/joc.5086
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Major rivers in a selected portion of Madagascar
Description
Spatial lines object of major rivers in a portion of Madagascar.
Usage
data(madRivers)
Format
An object of class sf
.
Source
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Rasters of average monthly maximum temperature for an eastern portion of Madagascar
Description
Rasters of maximum temperature for an eastern portion of Madagascar from WorldClim 2.1 at ~3.3 arcminute resolution projected to the Tananarive (Paris)/Laborde Grid coordinate reference system. Values represent monthly averages across 1970-2000. Units are in degrees C. These should not be used for formal analysis.
Format
An object of class SpatRaster
.
Source
References
Fick, S.E. and Hijmans, R.J. 2017. WorldClim 2: New 1-km spatial resolution climate surfaces for global land areas. International Journal of Climatology 37:4302-4315. doi:10.1002/joc.5086
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Rasters of average monthly minimum temperature for an eastern portion of Madagascar
Description
Rasters of minimum temperature for an eastern portion of Madagascar from WorldClim 2.1 at ~3.33 arcminute resolution projected to the Tananarive (Paris)/Laborde Grid coordinate reference system. Values represent monthly averages across 1970-2000. Units are in degrees C. These should not be used for formal analysis.
Format
An object of class SpatRaster
.
Source
References
Fick, S.E. and Hijmans, R.J. 2017. WorldClim 2: New 1-km spatial resolution climate surfaces for global land areas. International Journal of Climatology 37:4302-4315. doi:10.1002/joc.5086
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Mask values in a raster
Description
The output of mask()
is a GRaster
that has the same as values as the input raster. However, if the mask
argument is a GRaster
, the output will have NA
values in the same cells that the mask
raster has NA
cells. If the mask
argument is a GVector
, then the output raster will have NA
values in cells the GVector
does not cover.
Usage
## S4 method for signature 'GRaster,GRaster'
mask(x, mask, inverse = FALSE, maskvalues = NA, updatevalue = NA)
## S4 method for signature 'GRaster,GVector'
mask(x, mask, inverse = FALSE, updatevalue = NA)
Arguments
x |
A |
mask |
A |
inverse |
Logical: If |
maskvalues |
Numeric vector, including |
updatevalue |
Numeric, including |
Value
A GRaster
.
See Also
terra::mask()
, GRASS tool r.mask
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev") # raster
madForest <- fastData("madForest2000") # raster
madCoast <- fastData("madCoast4") # vector
# Convert to GRasters and GVectors
elev <- fast(madElev)
forest <- fast(madForest)
coast <- fast(madCoast)
ant <- coast[coast$NAME_4 == "Antanambe"]
# Mask by a raster or vector:
maskByRast <- mask(elev, forest)
plot(c(forest, maskByRast))
maskByVect <- mask(elev, ant)
plot(maskByVect)
plot(ant, add = TRUE)
# Mask by a raster or vector, but invert mask:
maskByRastInvert <- mask(elev, forest, inverse = TRUE)
plot(c(forest, maskByRastInvert))
maskByVectInvert <- mask(elev, ant, inverse = TRUE)
plot(maskByVectInvert)
plot(ant, add = TRUE)
# Mask by a raster, but use custom values for the mask:
maskByRastCustomMask <- mask(elev, elev, maskvalues = 1:20)
plot(c(elev <= 20, maskByRastCustomMask))
# Mask by a raster or vector, but force masked values to a custom value:
byRastCustomUpdate <- mask(elev, forest, updatevalue = 7)
plot(byRastCustomUpdate)
byVectCustomUpdate <- mask(elev, ant, updatevalue = 7)
plot(byVectCustomUpdate)
# Mask by a raster, inverse, custom values, and custom update:
byRastAll <-
mask(elev, elev, inverse = TRUE, maskvalues = 1:20, updatevalue = 7)
plot(c(elev, byRastAll))
}
Mask all non-NA cells or all NA cells
Description
This function converts all non-NA
cells in a GRaster
to a single user-defined value, leaving NA
cells as NA
. Alternatively, it can convert NA
cells to a user-defined value, and all non-NA
cells to NA.
Usage
## S4 method for signature 'GRaster'
maskNA(x, value = 1, invert = FALSE, retain = FALSE)
Arguments
x |
A |
value |
Numeric: Value to which to assign to masked cells. The default is 1. |
invert |
Logical: If |
retain |
Logical: If |
Value
A GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Convert non-NA to 1, NA cells remain NA
elevMask <- maskNA(elev)
elevMask
plot(c(elev, elevMask))
# Convert NA to 1, non-NA cells become NA
elevInvertMask <- maskNA(elev, invert = TRUE)
elevInvertMask
plot(c(elev, elevInvertMask))
# Convert NA to 200, non-NA cells keep their values
elevInvertRetain <- maskNA(elev, value = 200, invert = TRUE, retain = TRUE)
elevInvertRetain
plot(c(elev, elevInvertRetain))
}
Find which cells of a GRaster match certain values
Description
The match()
function takes a GRaster
and a numeric, integer or character vector as inputs and returns a GRaster
with cell values that correspond to the index of each element in the vector that matched the original cell value. For example, if a 4-cell raster had values 3, NA
, 5, 4, and the vector was c(3, 4)
, then the output would be a 4-cell raster with values 1, NA
, NA
, 2 because the first value in the vector was 3 (so the cell with 3 is assigned 1), and because the second value in the vector was 4 (so the cell with 4 was assigned 2). The other two values had no matches.
If the GRaster
is categorical, then the vector can be category labels instead of numeric values.
The %in%
operator returns a GRaster
with cell values that are 1 if their original values appeared in the vector, and 0 if not (or NA
if the original value was NA
). If the GRaster
is categorical, then the vector can be category labels instead of numeric values.
The %notin%
operator returns 1 for cells with values that are not found in the vector, and 0 otherwise. If the GRaster
is categorical, then the vector can be category labels instead of numeric values.
Usage
## S4 method for signature 'GRaster'
match(x, table, nomatch = NA)
## S4 method for signature 'GRaster'
x %in% table
## S4 method for signature 'GRaster'
x %notin% table
Arguments
x |
A |
table |
A numeric, integer, or character vector. |
nomatch |
Numeric or integer: Value to return when no match is found. |
Value
A GRaster
.
See Also
terra::match()
, match()
, omnibus::notIn()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Elevation and land cover rasters
madElev <- fastData("madElev")
madCover <- fastData("madCover")
### match() with an integer raster:
elev <- fast(madElev)
# Cells in elevation raster replaced with index in which they appear
# in the table:
table <- c(10, 20, 30, 40, 50)
elevIndex <- match(elev, table)
elevIndexNeg <- match(elev, table, nomatch = -100)
plot(c(elevIndex, elevIndexNeg))
### Using %in% and %notin% on an integer GRaster:
elev <- fast(madElev)
table <- c(10, 20, 30, 40, 50)
ins <- elev %in% table
notins <- elev %notin% table
plot(c(ins, notins))
### match() with a categorical raster:
cover <- fast(madCover)
cover <- droplevels(cover)
levels(cover)
forestLabels <- c(
"Sparse broadleaved evergreen/semi-deciduous forest",
"Broadleaved deciduous forest",
"Grassland with mosaic forest",
"Flooded forest"
)
forestClasses <- match(cover, forestLabels)
plot(forestClasses)
levels(forestClasses)
forestNoMatch <- match(cover, forestLabels, nomatch = -100)
plot(forestNoMatch)
levels(forestNoMatch)
### Using %in% and %notin% on a categorical GRaster:
cover <- fast(madCover)
cover <- droplevels(cover)
levels(cover)
forestLabels <- c(
"Sparse broadleaved evergreen/semi-deciduous forest",
"Broadleaved deciduous forest",
"Grassland with mosaic forest",
"Flooded forest"
)
forest <- cover %in% forestLabels
plot(forest)
notForest <- cover %notin% forestLabels
plot(notForest)
}
Mathematical operations on two or more GRasters
Description
These functions can be applied to a "stack" of GRaster
s with two or more layers. They return a single-layered GRaster
. If you want to summarize across cells in a raster (e.g., calculate the mean value of all cells on a raster), use global()
. Options include:
Numeration:
count()
(number of non-NA
cells),sum()
.Central tendency:
mean()
,mmode()
(mode),median()
.Extremes:
min()
,max()
,which.min()
(index of raster with the minimum value),which.max()
(index of the raster with the maximum value)Dispersion:
range()
,stdev()
(standard deviation),var()
(sample variance),varpop()
(population variance),nunique()
(number of unique values),quantile()
(use argumentprobs
),skewness()
, andkurtosis()
.-
NA
s:anyNA()
(any cells areNA
?),allNA()
(are all cellsNA
?)
Usage
## S4 method for signature 'GRaster'
mean(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
mmode(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
median(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
count(x)
## S4 method for signature 'GRaster'
sum(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
min(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
max(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
which.min(x)
## S4 method for signature 'GRaster'
which.max(x)
## S4 method for signature 'numeric'
sdpop(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
varpop(x, na.rm = FALSE)
## S4 method for signature 'numeric'
varpop(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
stdev(x, pop = TRUE, na.rm = FALSE)
## S4 method for signature 'GRaster'
var(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
nunique(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
skewness(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
kurtosis(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
range(x, na.rm = FALSE)
## S4 method for signature 'GRaster'
quantile(x, prob, na.rm = FALSE)
## S4 method for signature 'GRaster'
anyNA(x)
## S4 method for signature 'GRaster'
allNA(x)
Arguments
x |
A |
na.rm |
Logical: If |
pop |
Logical (for |
prob |
Numeric: Quantile to calculate. Used for |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster
chelsa <- fast(madChelsa)
chelsa # 4 layers
# Central tendency
mean(chelsa)
mmode(chelsa)
median(chelsa)
# Statistics
nunique(chelsa)
sum(chelsa)
count(chelsa)
min(chelsa)
max(chelsa)
range(chelsa)
skewness(chelsa)
kurtosis(chelsa)
stdev(chelsa)
stdev(chelsa, pop = FALSE)
var(chelsa)
varpop(chelsa)
# Which layers have maximum/minimum?
which.min(chelsa)
which.max(chelsa)
# Regression
# Note the intercept is different for fasterRaster::regress().
regress(chelsa)
regress(madChelsa, 1:nlyr(madChelsa))
# Note: To get quantiles for each layer, use global().
quantile(chelsa, 0.1)
# NAs
madForest2000 <- fastData("madForest2000")
forest2000 <- fast(madForest2000)
forest2000 <- project(forest2000, chelsa, method = "near")
chelsaForest <- c(chelsa, forest2000)
nas <- anyNA(chelsaForest)
plot(nas)
allNas <- allNA(chelsaForest)
plot(allNas)
}
Combine two or more rasters with different extents and fill in NAs
Description
merge()
combines two or more GRaster
s, possibly with different extents, into a single larger GRaster
. Where the same cell has different values in each raster, the value of the first raster's cell is used. If this is NA
, then the value of the second raster's cell is used, and so on.
Usage
## S4 method for signature 'GRaster,GRaster'
merge(x, y, ...)
Arguments
x , y , ... |
|
Value
A GRaster
.
See Also
terra::merge()
, terra::mosaic()
, and GRASS tool r.patch
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madCoast4 <- fastData("madCoast4")
madCoast4 <- vect(madCoast4)
# For the example, crop the elevation raster to two communes
madAnt <- madCoast4[madCoast4$NAME_4 == "Antanambe", ]
madMan <- madCoast4[madCoast4$NAME_4 == "Manompana", ]
elevAnt <- crop(madElev, madAnt)
elevMan <- crop(madElev, madMan)
plot(madElev)
plot(elevAnt, col = "red", legend = FALSE, add = TRUE)
plot(elevMan, col = "blue", legend = FALSE, add = TRUE)
# Convert a SpatRaster to a GRaster
ant <- fast(elevAnt)
man <- fast(elevMan)
# merge
antMan <- merge(ant, man)
plot(antMan, main = "Antman!")
}
Minimum and maximum values or categories of a GRaster
Description
minmax()
reports the minimum and maximum values across all non-NA cells of a GRaster
. When the levels
argument is TRUE
and the raster is categorical, the function reports the "lowest" and "highest" category values in a categorical (factor) GRaster
.
Usage
## S4 method for signature 'GRaster'
minmax(x, levels = FALSE)
Arguments
x |
A |
levels |
Logical: If |
Value
minmax()
returns a numeric matrix, and minmax(..., levels = TRUE)
returns a data.frame
with category names. In the latter case, non-categorical rasters will have NA
values.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Values in a categorical raster with no assigned category
Description
This function reports the values in a categorical GRaster
that have no matching category label in its "levels" table.
GRaster
s can represent categorical data. Cell values are actually integers, each corresponding to a category, such as "desert" or "wetland." A categorical raster is associated with a table that matches each value to a category name.
Usage
## S4 method for signature 'GRaster'
missingCats(x, layer = 1:nlyr(x))
Arguments
x |
A |
layer |
Numeric integers, logical vector, or character: Layer(s) for which to obtain missing categories. |
Value
A numeric vector (if x
is just one layer), or a named list of numeric vectors, one per layer in x
.
See Also
missingCats()
, missing.cases()
, droplevels()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Remove rasters and vectors from the GRASS cache
Description
fasterRaster functions attempt to delete rasters and vectors in the GRASS cache, but not all intermediate files can be removed. This function can be used to clear the cache of extraneous rasters and vectors.
Calling this function inside another function's environment and defining x
as "*"
can be very dangerous, as it will detect objects outside of that environment, and thus delete any rasters/vectors outside that environment. Here is a guide:
To delete files associated with a single
GRaster
orGVector
, usemow(GRaster_to_unlink)
ormow(GVector_to_unlink)
.To delete files associated with more than one
GRaster
s and/orGVector
s, provide them as a list. For example, usemow(list(GRaster_to_unlink, GVector_to_unlink))
.To remove all rasters, all vectors, or all rasters and vectors in the GRASS cache that are not linked to a
GRaster
orGVector
, usemow("*")
.To remove all rasters or all vectors in the GRASS cache, use
mow("*", type = "rasters")
ormow("*", type = "vectors")
.To remove all rasters or all vectors in the GRASS cache except for certain ones, use
mow("*", keep = list(GRaster_to_keep, GVector_to_keep))
. You can combine this with thekeep
argument to retain specific rasters or vectors. For example, you can usemow("*", type = "rasters", keep = list(GRaster_to_keep))
.
Usage
mow(
x = "unlinked",
pos = NULL,
type = NULL,
keep = NULL,
verbose = TRUE,
ask = TRUE
)
Arguments
x |
Any of:
|
pos |
Either |
type |
Either |
keep |
Either |
verbose |
Logical: If |
ask |
Logical: If |
Value
Invisibly returns a named vector with the number of rasters and vectors deleted.
See Also
Examples
if (grassStarted()) {
# Setup
madElev <- fastData("madElev")
elev <- fast(madElev)
mow(elev, ask = TRUE) # delete GRASS raster attached to `elev`
}
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.
Usage
## S4 method for signature 'GRaster,GRaster'
multivarEnvSim(ref, proj)
## S4 method for signature 'GRaster,missing'
multivarEnvSim(ref, proj)
## S4 method for signature 'data.frame,GRaster'
multivarEnvSim(ref, proj, na.rm = FALSE)
## S4 method for signature 'data.table,GRaster'
multivarEnvSim(ref, proj, na.rm = FALSE)
## S4 method for signature 'matrix,GRaster'
multivarEnvSim(ref, proj, na.rm = FALSE)
Arguments
ref |
A
|
proj |
A |
na.rm |
Logical: If |
Value
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)
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)
}
Number of NA or non-NA cells in a raster
Description
The nacell()
function counts the number of NA
cells in a GRaster
, and the nonnacell()
reports the number of non-NA
cells. If the raster is 3D, then all cells in all layers are counted.
Usage
## S4 method for signature 'GRaster'
nacell(x, warn = TRUE)
## S4 method for signature 'GRaster'
nonnacell(x, warn = TRUE)
Arguments
x |
A |
warn |
Logical: If |
Value
A numeric value, one per raster layer in the input.
See Also
ncell()
, ncell3d()
, terra::ncell()
, dim()
, terra::dim()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Name(s) of a GRaster or columns of a GVector's data table
Description
names()
returns that names(s) of a GRaster
or of columns of a GVector
's data table'.
Usage
## S4 method for signature 'GRaster'
names(x)
## S4 replacement method for signature 'GRaster'
names(x) <- value
## S4 method for signature 'GVector'
names(x)
## S4 replacement method for signature 'GVector'
names(x) <- value
Arguments
x |
A |
value |
Character: Name(s) to assign to the raster(s). |
Details
names(value) <-
assigns a new name to the GRaster
or to the columns of a GVector
's data table.
Value
Character vector.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
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.
Usage
## S4 method for signature 'GVector'
neighborhoodMatrix(x)
## S4 method for signature 'GVector'
neighbourhoodMatrix(x)
Arguments
x |
A polygons 'GVector. |
Value
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.
Examples
if (grassStarted()) {
# Setup
library(sf)
# Polygons vector:
madCoast4 <- fastData(madCoast4)
mc4 <- fast(madCoast4)
neighs <- neighborhoodMatrix(mc4)
neighs
}
Number of geometries and subgeometries in a vector
Description
GVector
s represent two types of "geometries". In "singlepart" geometries, each point, set of connected line segments, or polygon is treated like its own feature and has its own row in an attribute table. For example, a province might be composed of islands. In this case, each island would be represented as its own feature and could have its own row in the attribute indicating, say, the name and area of each island.
In "multipart" geometries, features are collected together and thu manipulated as if they were a single feature and have a singe line in an attribute table. Each multipart feature can contain one or more singlepart features. For example, all of the islands comprising province would be collated together and have a single row in the attribute table indicating the name of the province and the area of the entire province.
ngeom()
returns the number of geometries. Singlepart features are treated as one geometry each, and multipart features are treated as one geometry each.
nsubgeom()
Returns the number of subgeometries. Singlepart geometries each represent a single subgeometry. Multipart geometries represent one or more subgeometries. The number of subgeometries will thus always be the same as or more than the number of geometries.
Usage
## S4 method for signature 'GVector'
ngeom(x)
## S4 method for signature 'GVector'
nsubgeom(x)
Arguments
x |
A |
Value
An integer.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Number of categories in a categorical raster
Description
This function reports the number of categories (levels) in a categorical GRaster
.
Usage
## S4 method for signature 'GRaster'
nlevels(x)
Arguments
x |
A |
Value
A named, numeric vector of integers. The values represent the number of categories (rows) that appear in the raster's levels table.
See Also
levels()
, terra::levels()
, droplevels()
, vignette("GRasters", package = "fasterRaster")
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Land cover raster
madCover <- fastData("madCover")
# Convert categorical SpatRaster to categorical GRaster:
cover <- fast(madCover)
### Properties of categorical rasters
cover # note categories
is.factor(cover) # Is the raster categorical?
nlevels(cover) # number of levels
levels(cover) # just the value and active column
cats(cover) # all columns
minmax(cover) # min/max values
minmax(cover, levels = TRUE) # min/max categories
catNames(cover) # column names of the levels table
missingCats(cover) # categories in table with no values in raster
freq(cover) # frequency of each category (number of cells)
zonalGeog(cover) # geometric statistics
### Active column
# Which column sets the category labels?
activeCat(cover)
activeCat(cover, names = TRUE)
activeCats(c(cover, cover))
# Choose a different column for category labels:
levels(cover)
activeCat(cover) <- 2
levels(cover)
### Managing levels tables
# Remove unused levels:
nlevels(cover)
cover <- droplevels(cover)
nlevels(cover)
# Re-assign levels:
value <- c(20, 30, 40, 50, 120, 130, 140, 170)
label <- c("Cropland", "Cropland", "Forest", "Forest",
"Grassland", "Shrubland", "Herbaceous", "Flooded")
newCats <- data.frame(value = value, label = label)
cover <- categories(cover, layer = 1, value = newCats)
cats(cover)
# This is the same as:
levels(cover) <- newCats
cats(cover)
# Are there any values not assigned a category?
missingCats(cover)
# Let's assign a category for value 210 (water):
water <- data.frame(value = 210, label = "Water")
addCats(cover) <- water
levels(cover)
# Add more information to the levels table using merge():
landType <- data.frame(
Value = c(20, 30, 40, 50, 120),
Type = c("Irrigated", "Rainfed", "Broadleaf evergreen",
"Broadleaf deciduous", "Mosaic with forest")
)
cats(cover)
cover <- addCats(cover, landType, merge = TRUE)
cats(cover)
### Logical operations on categorical rasters
cover < "Forest" # 1 for cells with a value < 40, 0 otherwise
cover <= "Forest" # 1 for cells with a value < 120, 0 otherwise
cover == "Forest" # 1 for cells with value of 40-120, 0 otherwise
cover != "Forest" # 1 for cells with value that is not 40-120, 0 otherwise
cover > "Forest" # 1 for cells with a value > 120, 0 otherwise
cover >= "Forest" # 1 for cells with a value >= 120, 0 otherwise
cover %in% c("Cropland", "Forest") # 1 for cropland/forest cells, 0 otherwise
### Combine categories from different rasters
# For the example, will create a second categorical raster fromm elevation.
# Divide elevation raster into "low/medium/high" levels:
madElev <- fastData("madElev")
elev <- fast(madElev)
elev <- project(elev, cover, method = "near") # convert to same CRS
fun <- "= if(madElev < 100, 0, if(madElev < 400, 1, 2))"
elevCat <- app(elev, fun)
levs <- data.frame(
value = c(0, 1, 2),
elevation = c("low", "medium", "high")
)
levels(elevCat) <- list(levs)
# Combine levels:
combined <- concats(cover, elevCat)
combined
levels(combined)
# Combine levels, treating value/NA combinations as new categories:
combinedNA <- concats(cover, elevCat, na.rm = FALSE)
combinedNA
levels(combinedNA)
}
Scatterplot of values in each GRaster layer against the others
Description
pairs()
generates a scatterplot between values of cells in each layer of a GRaster
against all the other layers.
Usage
## S4 method for signature 'GRaster'
pairs(x, n = NULL, ...)
Arguments
x |
A |
n |
A numeric integer, integer, or |
... |
Arguments to send to
|
Value
Nothing (creates a plot).
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Retrieve a principal components model from a PCA GRaster
Description
Retrieve a principal components model from a PCA GRaster
Usage
pcs(x)
Arguments
x |
A |
Value
An object of class prcomp
.
See Also
princomp()
, terra::princomp()
, tool i.pca
in GRASS
Examples
if (grassStarted()) {
# Setup
library(terra)
# Climate raster:
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster:
chelsa <- fast(madChelsa)
# Generate raster with layers representing principal component predictions:
pcRast <- princomp(chelsa, scale = TRUE)
plot(pcRast)
# Get information on the PCA:
prinComp <- pcs(pcRast)
prinComp
summary(prinComp)
plot(prinComp)
}
Display a raster or vector
Description
plot()
displays a GRaster
or GVector
.
This function is essentially a hack, as it it not possible to dependably call the appropriate GRASS modules and display a raster or vector without potential confusion on the user side. Instead, this function 1) simplifies the focal GRaster
or GVector
to make it smaller when saved to disk; 2) writes the object to disk; 3) (internally) creates a SpatRaster
or SpatVector
object; then 4) plots the object using terra::plot()
. Thus, if you are interested in making maps, it will always be faster to make them directly with terra or sf.
Usage
## S4 method for signature 'GRaster,missing'
plot(x, y, simplify = TRUE, ...)
## S4 method for signature 'GVector,missing'
plot(x, y, maxGeoms = 10000, ...)
Arguments
x |
A |
y |
Missing–leave as empty. |
simplify |
Logical: If |
... |
Other arguments to send to |
maxGeoms |
Positive integer (vectors only): Maximum number of features before vector simplification is applied before saving to disk then creating a |
Value
Nothing (displays a raster or vector).
See Also
Examples
if (grassStarted()) {
# Example data
madElev <- fastData("madElev") # elevation raster
madLANDSAT <- fastData("madLANDSAT") # multi-layer raster
madRivers <- fastData("madRivers") # lines vector
# Convert SpatRaster to GRaster and SpatVector to GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
landsat <- fast(madLANDSAT)
# Plot:
plot(elev)
plot(rivers, add = TRUE)
# Histograms:
hist(elev)
hist(landsat)
# Plot surface reflectance in RGB:
plotRGB(landsat, 3, 2, 1) # "natural" color
plotRGB(landsat, 4, 1, 2, stretch = "lin") # emphasize near-infrared (vegetation)
# Make composite map from RGB layers and plot in grayscale:
comp <- compositeRGB(r = landsat[[3]], g = landsat[[2]], b = landsat[[1]])
grays <- paste0("gray", 0:100)
plot(comp, col = grays)
}
Create red-green-blue plot from a raster with RGB layers
Description
This function takes as its main argument a GRaster
with at least three layers typically representing red, green, and blue components (plus possibly an "alpha", or transparency layer). As with plot()
, this function is somewhat of a hack in that it downsamples the layers to a coarser resolution using aggregate()
, saves the raster to disk, then uses terra::plotRGB()
to do the actual plotting.
Usage
## S4 method for signature 'GRaster'
plotRGB(x, r = 1, g = 2, b = 3, a = NULL, simplify = TRUE, ...)
Arguments
x |
A |
r , g , b |
Either a numeric integer or the |
a |
Either |
simplify |
Logical: If |
... |
Arguments to pass to |
Value
Nothing (makes a plot).
See Also
terra::plotRGB()
, plot()
, compositeRGB()
Examples
if (grassStarted()) {
# Example data
madElev <- fastData("madElev") # elevation raster
madLANDSAT <- fastData("madLANDSAT") # multi-layer raster
madRivers <- fastData("madRivers") # lines vector
# Convert SpatRaster to GRaster and SpatVector to GVector
elev <- fast(madElev)
rivers <- fast(madRivers)
landsat <- fast(madLANDSAT)
# Plot:
plot(elev)
plot(rivers, add = TRUE)
# Histograms:
hist(elev)
hist(landsat)
# Plot surface reflectance in RGB:
plotRGB(landsat, 3, 2, 1) # "natural" color
plotRGB(landsat, 4, 1, 2, stretch = "lin") # emphasize near-infrared (vegetation)
# Make composite map from RGB layers and plot in grayscale:
comp <- compositeRGB(r = landsat[[3]], g = landsat[[2]], b = landsat[[1]])
grays <- paste0("gray", 0:100)
plot(comp, col = grays)
}
Make predictions from a linear or generalized linear model to a GRaster
Description
This version of the predict()
function make predictions to a set of GRaster
s from a model object.
The model must be either a linear model, which is of class lm
and typically created using the stats::lm()
function or a generalized linear model (GLM), which is class glm
and typically created using stats::glm()
. Other packages can also create lm
or glm
objects, but they may not work in this function. For example, generalized additive models, which can be created using the gam()
function in the mgcv package, inherit the glm
class, but cannot be used in this function. However, glm
objects created with the speedglm package should work with this function.
This predict()
function can handle:
Linear predictors and intercepts like
1 + x
;Quadratic terms like
x^2
(or, in R formula notation,I(x^2)
);Two-way interaction terms between scalars like
x1:x2
andx1 * x2
;Categorical predictors (i.e., categorical
GRaster
s; seevignette("GRasters", package = "fasterRaster")
);Two-way interactions between a categorical predictor and a scalar predictor; and
Two-way interactions between categorical predictors.
Usage
## S4 method for signature 'GRaster'
predict(object, model, type = "response")
Arguments
object |
A |
model |
An |
type |
Character: Type of prediction to make. This can be either |
Value
A GRaster
.
See Also
terra::predict()
; stats::predict()
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
### This example creates a simple model of Dypsis distribution using
# elevation, distance to forest, land cover class, and nearness to rivers.
# Elevation raster, forest cover in year 2000, land cover class, and
# points where Dypsis plants have been collected
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCover <- fastData("madCover")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert SpatRasters to GRasters and sf vectors to GVectors:
elev <- fast(madElev)
forest <- fast(madForest2000)
cover <- fast(madCover)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Distance to forest
distToForest <- distance(forest, unit = "m")
distToForest <- log1p(distToForest) # log(x + 1) of distance
names(distToForest) <- "distToForest"
# "Stack" elevation and forest cover
continuous <- c(elev, distToForest)
# Scale continuous predictors to mean of 0 and sd of 1
continuousScaled <- scale(continuous)
names(continuousScaled) <- c("elevation", "distToForest")
# Project land cover raster
coverProj <- project(cover, continuousScaled)
# Near a river?
riverBuffer <- buffer(rivers, 5000)
nearRiver <- rasterize(riverBuffer, elev, background = 0)
names(nearRiver) <- "nearRiver"
levels(nearRiver) <- data.frame(value = 0:1, label = c("far", "near"))
# Combine continuous/categorical data
covariateRasters <- c(continuousScaled, coverProj, nearRiver)
plot(covariateRasters)
# Extract environmental values at Dypsis locations:
presEnv <- extract(covariateRasters, dypsis, cats = TRUE)
presEnv$presBg <- 1
head(presEnv)
# Extract elevation and forest cover at 2000 background sites:
bgEnv <- spatSample(covariateRasters, size = 3000, values = TRUE, cats = TRUE)
bgEnv <- bgEnv[stats::complete.cases(bgEnv), ]
bgEnv <- bgEnv[1:2000, ]
bgEnv$presBg <- 0
head(bgEnv)
# Combine presence and background data:
env <- rbind(presEnv, bgEnv)
# Calibrate model:
form <- presBg ~ elevation + distToForest +
I(distToForest^2) + elevation * distToForest +
madCover + nearRiver
model <- stats::glm(form, data = env, family = stats::binomial)
summary(model)
# Make predictions and map:
prediction <- predict(covariateRasters, model, type = "response")
prediction
# Not a great model!
plot(prediction, main = "Predicted")
plot(dypsis, pch = 1, add = TRUE)
}
Apply a principal component analysis (PCA) to layers of a GRaster
Description
This function applies a principal component analysis to layers of a GRaster
.
Usage
## S4 method for signature 'GRaster'
princomp(x, scale = TRUE, scores = FALSE)
Arguments
x |
A |
scale |
Logical: If |
scores |
Logical: If |
Value
A multi-layer GRaster
with one layer per principal component axis. The pcs()
function can be used on the output raster to retrieve a prcomp
object from the raster, which includes rotations (loadings) and proportions of variance explained.
See Also
terra::princomp()
, terra::prcomp()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Climate raster:
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster:
chelsa <- fast(madChelsa)
# Generate raster with layers representing principal component predictions:
pcRast <- princomp(chelsa, scale = TRUE)
plot(pcRast)
# Get information on the PCA:
prinComp <- pcs(pcRast)
prinComp
summary(prinComp)
plot(prinComp)
}
Display a fasterRaster object
Description
Display a GLocation
, GSpatial
, GRegion
, GRaster
, or GVector
object.
Usage
## S3 method for class 'rastInfo'
print(x, ...)
show.rastInfo(x)
## S3 method for class 'vectInfo'
print(x, ...)
## S3 method for class 'vectInfo'
show(x)
## S4 method for signature 'GLocation'
show(object)
## S3 method for class 'GLocation'
print(x, ...)
## S4 method for signature 'GLocation'
summary(object)
## S4 method for signature 'GSpatial'
show(object)
## S3 method for class 'GSpatial'
print(x, ...)
## S4 method for signature 'GSpatial'
summary(object)
## S4 method for signature 'GRegion'
show(object)
## S3 method for class 'GRegion'
print(x, ...)
## S4 method for signature 'GRegion'
summary(object)
## S4 method for signature 'GRaster'
show(object)
## S3 method for class 'GRaster'
print(x, ...)
## S4 method for signature 'GRaster'
summary(object)
## S4 method for signature 'GVector'
show(object)
## S3 method for class 'GVector'
print(x, ...)
## S4 method for signature 'GVector'
summary(object)
Arguments
... |
Other arguments. |
object , x |
An object of class |
Value
Nothing (side effect is to display metadata on the given object).
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCoast0 <- fastData("madCoast0")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
### GRaster properties
# convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
# plot
plot(elev)
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
topology(elev) # number of dimensions
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
minmax(elev) # min/max values
# name of object in GRASS
sources(elev)
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
# extent (bounding box)
ext(elev)
# data type
datatype(elev)
# assigning
copy <- elev
copy[] <- pi # assign all cells to the value of pi
copy
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# adding a raster "in place"
add(rasts) <- ln(elev)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# assigning
rasts[[4]] <- elev > 500
# number of layers
nlyr(rasts)
# names
names(rasts)
names(rasts) <- c("elev_meters", "forest", "ln_elev", "high_elevation")
rasts
### GVector properties
# convert sf vectors to GVectors
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# extent
ext(rivers)
W(rivers) # western extent
E(rivers) # eastern extent
S(rivers) # southern extent
N(rivers) # northern extent
top(rivers) # top extent (NA for 2D rasters like this one)
bottom(rivers) # bottom extent (NA for 2D rasters like this one)
# coordinate reference system
crs(rivers)
st_crs(rivers)
# column names and data types
names(coast)
datatype(coast)
# name of object in GRASS
sources(rivers)
# points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# dimensions
nrow(rivers) # how many spatial features
ncol(rivers) # hay many columns in the data frame
# number of geometries and sub-geometries
ngeom(coast)
nsubgeom(coast)
# 2- or 3D
topology(rivers) # dimensionality
is.2d(elev) # is it 2D?
is.3d(elev) # is it 3D?
# Update values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case)
coast <- update(coast)
### operations on GVectors
# convert to data frame
as.data.frame(rivers)
as.data.table(rivers)
# subsetting
rivers[c(1:2, 5)] # select 3 rows/geometries
rivers[-5:-11] # remove rows/geometries 5 through 11
rivers[ , 1] # column 1
rivers[ , "NAM"] # select column
rivers[["NAM"]] # select column
rivers[1, 2:3] # row/geometry 1 and column 2 and 3
rivers[c(TRUE, FALSE)] # select every other geometry (T/F vector is recycled)
rivers[ , c(TRUE, FALSE)] # select every other column (T/F vector is recycled)
# removing data table
noTable <- dropTable(rivers)
noTable
nrow(rivers)
nrow(noTable)
# Refresh values from GRASS
# (Reads values from GRASS... will not appear to do anything in this case
# since the rivers object is up-to-date):
rivers <- update(rivers)
# Concatenating multiple vectors
rivers2 <- rbind(rivers, rivers)
dim(rivers)
dim(rivers2)
}
Change the coordinate reference system of a GRaster or GVector
Description
project()
changes the coordinate reference system (CRS) of a GRaster
or GVector
. It has three use cases:
-
x
is aGRaster
andy
is aGRaster
:x
will be projected to the CRS ofy
and resampled to have the same resolution asy
. If argumentalign
isFALSE
, then it will also be cropped to the extent ofy
. -
x
is aGRaster
andy
is aGVector
or a CRS string (typically in Well-Known Text format):x
will be projected to the CRS specified byy
and resampled but not cropped. -
x
is aGVector
andy
is aGRaster
,GVector
, or CRS string: The vector will be projected to the CRS ofy
.
Usage
## S4 method for signature 'GRaster'
project(
x,
y,
align = FALSE,
method = NULL,
fallback = TRUE,
res = "fallback",
wrap = FALSE,
verbose = FALSE
)
## S4 method for signature 'GVector'
project(x, y, wrap = FALSE)
Arguments
x |
A |
y |
A character or |
align |
Logical: If |
method |
Character or
Note #1: If Note #2: Methods that use multiple cells will cause the focal cell to become |
fallback |
Logical (for projecting |
res |
Character (for projecting
|
wrap |
Logical:
|
verbose |
Logical (for projecting |
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.
Value
A GRaster
or GVector
.
See Also
terra::project()
, sf::st_transform()
, GRASS manual pages for modules r.proj
and v.proj
(see grassHelp("r.proj")
and grassHelp("v.proj")
)
Examples
if (grassStarted()) {
### Setup for all examples
library(sf)
library(terra)
# Climate raster, elevation raster, rivers vector
madElev <- fastData("madElev")
madRivers <- fastData("madRivers")
madChelsa <- fastData("madChelsa")
# Convert objects into fasterRaster formats
chelsa <- fast(madChelsa)
elev <- fast(madElev)
rivers <- fast(madRivers)
### Project raster without resampling
elevWGS84 <- project(elev, crs(chelsa))
elevWGS84
### Project raster and resample to resolution of another raster
elevWGS84Resamp <- project(elev, chelsa)
elevWGS84Resamp
res(elevWGS84)
res(elevWGS84Resamp)
res(chelsa)
### Project vector
riversWGS84 <- project(rivers, chelsa)
riversWGS84
cat(crs(rivers)) # using "cat()" to make it look nice
cat(crs(riversWGS84))
}
Create a raster with random values drawn from a normal distribution
Description
rNormRast()
creates a raster with values drawn from a normal distribution.
Usage
## S4 method for signature 'GRaster'
rNormRast(x, n = 1, mu = 0, sigma = 1, seed = NULL)
Arguments
x |
A |
n |
An integer: Number of rasters to generate. |
mu , sigma |
Numeric: Mean and sample standard deviation of output. If creating more than one raster, you can provide one value per raster. If there are fewer, they will be recycled. |
seed |
Numeric integer or |
Value
A GRaster
.
See Also
rSpatialDepRast()
, fractalRast()
, rUnifRast()
, rWalkRast()
, GRASS manual page for tool r.random.surface
(see grassHelp("r.random.surface")
)
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)
}
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.
Usage
## S4 method for signature 'GRaster'
rSpatialDepRast(
x,
n = 1,
mu = 0,
sigma = 1,
dist = 0,
exponent = 1,
delay = 0,
seed = NULL
)
Arguments
x |
A |
n |
An integer: Number of rasters to generate. |
mu , sigma |
Numeric: Mean and sample standard deviation of output. If creating more than one raster, you can provide one value per raster. If there are fewer, they will be recycled. |
dist |
Numeric: Maximum distance of spatial autocorrelation (in map units–typically meters). Default is 0 (no spatial autocorrelation). If creating more than one raster, you can provide one value per raster. If there are fewer, values will be recycled. |
exponent |
Numeric > 0: Distance decay exponent. If creating more than one raster, you can provide one value per raster. If there are fewer, values will be recycled. |
delay |
Numeric >= 0: Values >0 force the distance decay of similarity to remain constant up to this distance. Beyond this distance, the decay exponent takes effect. Default is 0. If creating more than one raster, you can provide one value per raster. If there are fewer, values will be recycled. |
seed |
Numeric integer or |
Value
A GRaster
.
See Also
rNormRast()
, fractalRast()
, rUnifRast()
, rWalkRast()
, GRASS manual page for tool r.random.surface
(see grassHelp("r.random.surface")
)
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)
}
Create a raster with random values drawn from a uniform distribution
Description
rUnifRast()
creates a raster with values drawn from a uniform (flat) distribution.
Usage
## S4 method for signature 'GRaster'
rUnifRast(x, n = 1, low = 0, high = 1, seed = NULL)
Arguments
x |
A |
n |
A numeric integer: Number of rasters to generate. |
low , high |
Numeric: Minimum and maximum values from which to select. |
seed |
Numeric integer vector or |
Value
A GRaster
.
See Also
rNormRast()
, rSpatialDepRast()
, fractalRast()
, rWalkRast()
, GRASS manual page for tool r.random.surface
(see grassHelp("r.random.surface")
)
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)
}
Create raster representing one or more random walks
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 fasterRaster to use multiple cores and more memory using the "cores" and "memory" arguments in the faster()
function.
Usage
## S4 method for signature 'GRaster'
rWalkRast(
x,
n = 1,
steps = 1e+05,
directions = 8,
avoid = FALSE,
sameStart = FALSE,
seed = NULL,
check = TRUE
)
Arguments
x |
A |
n |
Numeric: Number of walkers. Default is 1. |
steps |
Numeric: Number of steps taken by each walker. Default is 100000. |
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). |
avoid |
Logical: If |
sameStart |
Logical: If |
seed |
Integer or |
check |
Logical: If |
Details
This function needs the GRASS addon r.random.walk
. If it is not installed, it will try to install it.#'
Value
A GRaster
with cell values representing the number of times one or more walkers traversed the cell.
See Also
rNormRast()
, rUnifRast()
, rSpatialDepRast()
, fractalRast()
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)
}
Convert a GRaster to a SpatRaster
Description
The fasterRaster version of the rast()
function converts a GRaster
to a SpatRaster
(from the terra package).
Usage
## S4 method for signature 'GRaster'
rast(x, mm = FALSE, ...)
Arguments
x |
A |
mm |
Logical: If |
... |
Additional arguments to send to |
Value
A SpatRaster
(terra package).
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Convert a GVector to a GRaster
Description
The rasterize()
function converts a GVector
into a GRaster
.
Usage
## S4 method for signature 'GVector,GRaster'
rasterize(x, y, field = "", background = NA, by = NULL, verbose = TRUE)
Arguments
x |
A |
y |
A |
field |
Character: Name of a column in the data table of |
background |
Numeric or |
by |
Either |
verbose |
Logical: If |
Value
A GRaster
.
See Also
terra::rasterize()
, GRASS tool v.to.rast
(see grassHelp("v.to.rast")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster, outline of a part of Madagascar, and rivers vector:
madElev <- fastData("madElev") # raster
madDypsis <- fastData("madDypsis") # points vector
madRivers <- fastData("madRivers") # lines vector
madCoast4 <- fastData("madCoast4") # polygons vector
# Convert to GRaster and GVectors:
elev <- fast(madElev)
dypsis <- fast(madDypsis)
coast4 <- fast(madCoast4)
rivers <- fast(madRivers)
# Convert points, line, and polygons vectors to rasters:
points <- rasterize(dypsis, elev)
plot(points)
lines <- rasterize(rivers, elev)
plot(lines)
polys <- rasterize(coast4, elev)
plot(polys)
communes <- rasterize(coast4, elev, field = "NAME_4")
plot(communes)
# Change background value:
polysNeg1 <- rasterize(coast4, elev, background = -1)
plot(polysNeg1)
# Make one layer per river:
byRiver <- rasterize(rivers, elev, field = "NAM", by = "NAM")
plot(byRiver)
}
Combine one or more GVectors
Description
rbind()
combines two or more GVector
s of the same type (points, lines, or polygons) and same coordinate reference system. You can speed operations by putting the vector that is largest in memory first in rbind(...)
. If the GVector
s have data tables, these will also be combined using rbind()
if their column names and data types match.
Usage
## S4 method for signature 'GVector'
rbind(..., deparse.level = 1)
Arguments
... |
One or more |
deparse.level |
See |
Value
A GVector
.
See Also
colbind()
, addTable<-
, dropTable()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Rivers vector
madRivers <- fastData("madRivers")
# Convert sf to a GVector
rivers <- fast(madRivers)
# Convert GVector to data.frame or data.table
as.data.frame(rivers)
as.data.table(rivers)
# Subset rivers vector
rivers1 <- rivers[1:2]
rivers2 <- rivers[10:11]
# Concatenate rivers
riversCombo <- rbind(rivers1, rivers2)
riversCombo
# Add columns
newCol <- data.frame(new = 1:11)
riversCol <- colbind(rivers, newCol)
riversCol
# Remove table
riversCopy <- rivers
riversCopy # has data table
riversCopy <- dropTable(riversCopy)
riversCopy # no data table
# Add a new table
newTable <- data.frame(num = 1:11, letters = letters[1:11])
addTable(riversCopy) <- newTable
riversCopy
}
Regression intercept, slope, r2, and t-value across each set of cells
Description
This function performs a regression on each set of cells in a multi-layered GRaster
. The output is a GRaster
with the intercept, slope, r^2 value, and Student's t value. The regression formula is as y ~ 1 + x
, where x
is the layer number of each layer (e.g., 1 for the first or top layer in the input GRaster
, 2 for the second or second-to-top layer, etc.). Note that this is restricted version of the functionality in terra::regress()
.
Usage
## S4 method for signature 'GRaster,missing'
regress(y, x, na.rm = FALSE)
Arguments
y |
A multi-layer |
x |
Ignored. |
na.rm |
Logical: If |
Value
A multi-layer GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madChelsa <- fastData("madChelsa")
# Convert a SpatRaster to a GRaster
chelsa <- fast(madChelsa)
chelsa # 4 layers
# Central tendency
mean(chelsa)
mmode(chelsa)
median(chelsa)
# Statistics
nunique(chelsa)
sum(chelsa)
count(chelsa)
min(chelsa)
max(chelsa)
range(chelsa)
skewness(chelsa)
kurtosis(chelsa)
stdev(chelsa)
stdev(chelsa, pop = FALSE)
var(chelsa)
varpop(chelsa)
# Which layers have maximum/minimum?
which.min(chelsa)
which.max(chelsa)
# Regression
# Note the intercept is different for fasterRaster::regress().
regress(chelsa)
regress(madChelsa, 1:nlyr(madChelsa))
# Note: To get quantiles for each layer, use global().
quantile(chelsa, 0.1)
# NAs
madForest2000 <- fastData("madForest2000")
forest2000 <- fast(madForest2000)
forest2000 <- project(forest2000, chelsa, method = "near")
chelsaForest <- c(chelsa, forest2000)
nas <- anyNA(chelsaForest)
plot(nas)
allNas <- allNA(chelsaForest)
plot(allNas)
}
Convert degrees between 'north-orientation' and 'east orientation'
Description
This function converts facing between "north orientation" and "east orientation".
In "north orientation" systems, a 0-degree facing is north, and the angle of facing proceeds clockwise. For example, a 90 degree facing faces east, 180 south, and 270 west. In "east orientation", a 0-degree facing is east, and the facing angle proceeds counter-clockwise. For example, 90 is north, 180 is west, and 270 south.
Usage
## S4 method for signature 'GRaster'
reorient(x, units = "degrees")
## S4 method for signature 'numeric'
reorient(x, units = "degrees")
Arguments
x |
A numeric vector or a |
units |
Character: "Units" of values in |
Value
A GRaster
or numeric vector. Values will be in the range between 0 and 360 and represents facing in the system "opposing" the input's system. For example, if the input is north orientation, the output will be east orientation. If the input is in east orientation, the output will be in north orientation.
Examples
### Re-orient numeric values:
facings <- c(0, 90, 180, 270, 360)
reorient(facings)
# Re-reorienting returns the same values:
reorient(reorient(facings))
if (grassStarted()) {
### Re-orient a GRaster:
# Setup
library(terra)
madElev <- fastData("madElev")
elev <- fast(madElev)
# Calculate aspect in degrees, using north orientation:
aspectNorth <- terrain(elev, "aspect")
# Re-orient to east-facing:
aspectEast <- reorient(aspectNorth)
# Re-reorienting is the same, to within rounding error:
aspectNorth - reorient(reorient(aspectNorth))
# Plot:
aspects <- c(aspectNorth, aspectEast)
names(aspects) <- c("north_orientation", "east_orientation")
plot(aspects)
}
Replace NAs in a data.table or data.frame column, or in a vector
Description
This function replaces NA
s in one or more data.table
, data.frame
, or matrix
columns, or in vectors, with a user-defined value.
Usage
## S4 method for signature 'data.frame'
replaceNAs(x, replace, cols = NULL)
## S4 method for signature 'matrix'
replaceNAs(x, replace, cols = NULL)
## S4 method for signature 'data.table'
replaceNAs(x, replace, cols = NULL)
## S4 method for signature 'numeric'
replaceNAs(x, replace)
## S4 method for signature 'integer'
replaceNAs(x, replace)
## S4 method for signature 'logical'
replaceNAs(x, replace)
## S4 method for signature 'character'
replaceNAs(x, replace)
Arguments
x |
A |
replace |
A value of any atomic class (numeric, integer, character, Date, etc.): Value to to replace |
cols |
|
Value
A data.table
, data.frame
, matrix
, or vector.
Examples
library(data.table)
dt <- data.table(
x = 1:10,
y = letters[1:10],
z = rnorm(10)
)
# make some values NA
dt[x == 4 | x == 8, y := NA_character_]
dt
# Replace NAs:
replaceNAs(dt, replace = -99, cols = "y")
dt
# Drop rows:
dropped <- dropRows(dt, 8:10)
dropped
# NB May not print... in that case, use:
print(dropped)
# We can also use replaceNAs() on vectors:
y <- 1:10
y[c(2, 10)] <- NA
replaceNAs(y, -99)
# Same as:
y <- 1:10
y[c(2, 10)] <- NA
y[is.na(y)] <- -99
Spatial resolution
Description
Spatial resolution of a GRaster
:
-
res()
: 2-dimensional resolution (x and y).
-
res3d()
: 3-dimensional resolution (z, y, and z).
-
xres()
,yres()
, andzres()
: East-west resolution, north-south resolution, and top-bottom resolution.
Usage
## S4 method for signature 'missing'
res(x)
## S4 method for signature 'GRegion'
res(x)
## S4 method for signature 'missing'
xres(x)
## S4 method for signature 'GRegion'
xres(x)
## S4 method for signature 'missing'
yres(x)
## S4 method for signature 'GRegion'
yres(x)
## S4 method for signature 'missing'
zres(x)
## S4 method for signature 'GRegion'
zres(x)
## S4 method for signature 'missing'
res3d(x)
## S4 method for signature 'GRegion'
res3d(x)
Arguments
x |
A |
Value
A numeric vector. For both res()
and res3d()
, the first value is the length of cells in the x-direction and the second the length of cells in the y-direction. For res3d()
the third value is height of a voxel (the z-direction). xres()
, yres()
, and zres()
each return a single value.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Change the cell size of a GRaster
Description
resample()
changes the cell size (resolution) of a GRaster
using either another raster as a template or a user-defined resolution. Note that the extent of the output raster may be expanded to accommodate an integer number of cells. The function is not guaranteed to recreate the same output as terra::resample()
, even when the same resampling method is used.
Usage
## S4 method for signature 'GRaster,GRaster'
resample(x, y, method = NULL, fallback = TRUE)
## S4 method for signature 'GRaster,numeric'
resample(x, y, method = NULL, fallback = TRUE)
Arguments
x |
The |
y |
Either a |
method |
Character or
|
fallback |
Logical: If |
Value
A GRaster
.
See Also
terra::resample()
, GRASS modules r.resample
and r.resamp.interp
(see grassHelp("
r.resample") and
grassHelp("r.resamp.interp
")')
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
elev <- fast(madElev)
### Resample raster to 120 x 120 m
elev120 <- resample(elev, c(120, 120), method="bilinear")
elev
elev120
### Resample using another raster as a template
template <- aggregate(elev, 4)
nearest <- resample(elev, template, method = "nearest")
bilinear <- resample(elev, template, method = "bilinear")
bilinearNoFB <- resample(elev, template, method = "bilinear", fallback = FALSE)
bicubic <- resample(elev, template, method = "bicubic")
bicubicNoFB <- resample(elev, template, method = "bicubic", fallback = FALSE)
lanczos <- resample(elev, template, method = "lanczos")
lanczosNoFB <- resample(elev, template, method = "lanczos", fallback = FALSE)
# rasters resampled without fallback have fewer non-NA cells
resampled <- c(nearest, bilinear, bilinearNoFB, bicubic, bicubicNoFB, lanczos,
lanczosNoFB)
names(resampled) <- c("nearest", "bilinear", "bilinearNoFB", "bicubic",
"bicubicNoFB", "lanczos", "lanczosNoFB")
ones <- resampled * 0 + 1
global(ones, "sum") # number of non-NA cells
global(resampled, c("mean", "sd", "min", "max")) # other statistics
# Compare fallback to no fallback
frLanczos <- rast(lanczos)
frLanczosNoFB <- rast(lanczosNoFB)
plot(frLanczos, col = "red",
main = "Red: Cells in fallback not non-fallback", legend = FALSE)
plot(frLanczosNoFB, add=TRUE)
# Compare fasterRaster with terra
coarserTerra <- aggregate(madElev, 4)
terraLanczos <- resample(madElev, coarserTerra, method = "lanczos")
frLanczos <- extend(frLanczos, terraLanczos)
frLanczosNoFB <- extend(frLanczosNoFB, terraLanczos)
frLanczos - terraLanczos
frLanczosNoFB - terraLanczos
plot(frLanczos - terraLanczos, main = "Difference")
plot(frLanczosNoFB - terraLanczos, main = "Difference")
plot(terraLanczos, col = "red",
main = "Red: Cells in terra not in FR", legend = FALSE)
plot(frLanczos, add=TRUE)
plot(frLanczos, col = "red",
main = "Red: Cells in FR not in terra", legend = FALSE)
plot(terraLanczos, add=TRUE)
}
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
\sqrt(\sum_{i = 1}^{8}(m_i - m_0)^2 / 8)
where m_0
is the elevation of the focal cell and m_i
is the elevation of the ith 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.
Usage
## S4 method for signature 'GRaster'
ruggedness(x, size = 3, exponent = 0)
Arguments
x |
A |
size |
Integer (default is 3): Size of the moving window. Must be an odd integer >= 3. |
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 |
Value
A GRaster
.
References
Riley, S.J., DeGloria, S.D., and Elliot, R. 1999. A terrain ruggedness index that quantifies topographic heterogeneity. Intermountain Journal of Sciences 5:23-27.
See Also
terrain()
, wetness()
, geomorphons()
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert to GRaster:
elev <- fast(madElev)
# 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)
}
Create a randomly-positioned tesselation
Description
This function partitions a region into Voronoi polygons that completely overlap it. Each polygon has a random center. The function is essentially a wrapper for spatSample()
and voronoi()
.
Usage
## S4 method for signature 'GRaster'
rvoronoi(x, size = 100, seed = NULL)
## S4 method for signature 'GVector'
rvoronoi(x, size = 100, seed = NULL)
Arguments
x |
A |
size |
Numeric integer or integer: Number of polygons. |
seed |
Numeric integer, integer, or |
Value
A GVector
.
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example vectors
madDypsis <- fastData("madDypsis") # points
madCoast4 <- fastData("madCoast4") # polygons
# Convert sf vectors to GVectors
dypsis <- fast(madDypsis)
coast4 <- fast(madCoast4)
ant <- coast4[coast4$NAME_4 == "Antanambe"]
# Delaunay triangulation
dypsisDel <- delaunay(dypsis)
plot(dypsisDel)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Voronoi tessellation
vor <- voronoi(dypsis)
plot(vor)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Random Voronoi tessellation
rand <- rvoronoi(coast4, size = 100)
plot(rand)
}
Randomly sample cells from a GRaster
Description
sampleRast()
randomly samples cells from non-NA
cells of a raster. The output will be a raster with selected non-NA
cells, and all other cells set to NA
. To generate random points, see spatSample()
.
Usage
## S4 method for signature 'GRaster'
sampleRast(
x,
size,
prop = FALSE,
maskvalues = NA,
updatevalue = NULL,
test = FALSE,
seed = NULL
)
Arguments
x |
A |
size |
Numeric: Number of cells or proportion of cells to select. |
prop |
Logical: If |
maskvalues |
Numeric vector, including |
updatevalue |
Numeric or |
test |
Logical: If |
seed |
|
Value
A GRaster
.
See Also
spatSample()
; terra::spatSample()
, tool r.random
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev") # raster
# Convert to GRasters and GVectors
elev <- fast(madElev)
### spatSample()
# Random points as data.frame or data.table:
randVals <- spatSample(elev, size = 20, values = TRUE)
randVals
# Random points as a points GVector:
randPoints <- spatSample(elev, size = 20, as.points = TRUE)
randPoints
plot(elev)
plot(randPoints, add = TRUE)
# Random points in a select area:
madCoast <- fastData("madCoast4") # vector
coast <- fast(madCoast)
ant <- coast[coast$NAME_4 == "Antanambe"] # subset
restrictedPoints <- spatSample(elev, size = 20, as.points = TRUE,
strata = ant)
plot(elev)
plot(ant, add = TRUE)
plot(restrictedPoints, add = TRUE) # note 20 points for entire geometry
# Random points, one set per subgeometry:
stratifiedPoints <- spatSample(elev, size = 20, as.points = TRUE,
strata = ant, byStratum = TRUE)
plot(elev)
plot(ant, add = TRUE)
plot(stratifiedPoints, pch = 21, bg = "red", add = TRUE) # note 20 points per subgeometry
# Random categories:
madCover <- fastData("madCover") # raster
cover <- fast(madCover)
randCover <- spatSample(cover, size = 20, values = TRUE,
cat = TRUE, xy = TRUE)
randCover
### sampleRast()
# Random cells in non-NA cells:
rand <- sampleRast(elev, 10000)
plot(rand)
nonnacell(rand)
# Use custom values for the mask:
randCustomMask <- sampleRast(elev, 10000, maskvalues = 1:20)
plot(randCustomMask)
# Force selected values to a custom value:
randCustomUpdate <- sampleRast(elev, 10000, updatevalue = 7)
plot(randCustomUpdate)
# Custom values for mask and set selected cells to custom value:
randAll <- sampleRast(elev, 10000, maskvalues = 1:20, updatevalue = 7)
plot(randAll)
}
Center and scale a GRaster, or the opposite
Description
scale()
and scalepop()
center and scale layers in a GRaster
by subtracting from each raster its mean value (centering), then dividing by its standard deviation (scaling). This is useful for using the raster in a linear model, for example, because unscaled predictors can lead to numerical instability. The scale()
function uses the sample standard deviation, and the scalepop()
function uses the population standard deviation. For even moderately-sized rasters, the difference between these two is negligible, but the scalepop()
function can be much faster than the scale()
function.
The unscale()
function does the opposite of scale()
and scalepop()
: it multiples each layer by a value (presumably, its standard deviation), and adds another value (presumably, its mean).
Usage
## S4 method for signature 'GRaster'
scale(x, center = TRUE, scale = TRUE)
## S4 method for signature 'GRaster'
scalepop(x, center = TRUE, scale = TRUE)
## S4 method for signature 'GRaster'
unscale(x, center = NULL, scale = NULL)
Arguments
x |
A |
center |
Value depends on the function:
|
scale |
Value depends on the function:
|
Value
All functions return a GRaster
. The output of scale()
and scalepop()
will have two attributes, "center" and "scale", which have the means and standard deviations of the original rasters (if center
and scale
are TRUE
, otherwise, they will be NA
). These can be obtained using attributes(output_raster)$center
and attributes(output_raster)$scale
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Climate rasters:
madChelsa <- fastData("madChelsa")
# Convert to GRasters:
chelsa <- fast(madChelsa)
### Center and scale rasters
# Scale with using sample SD:
chScaled <- scale(chelsa)
chScaled
# Scale with using population SD:
chScaledPop <- scalepop(chelsa)
chScaledPop
# Means are very close to 0 and SDs to 1:
global(chScaled, c("mean", "sd", "min", "max"))
global(chScaledPop, c("mean", "sd", "min", "max"))
# Get original means and sd's:
centers <- attributes(chScaled)$center
scales <- attributes(chScaled)$scale
centers
scales
### Unscale rasters:
chUnscaled <- unscale(chScaled, center = centers, scale = scales)
# Means and SD are returned to original values:
global(chUnscaled, c("mean", "sd", "min", "max")) # unscaled
global(chelsa, c("mean", "sd", "min", "max")) # original
}
Create one GRaster layer per unique value in a GRaster
Description
This function creates a multi-layered GRaster
for every unique values in an input GRaster
. By default, the output will have a value of 1 wherever the input has the given value, and 0 elsewhere. This is useful for creating dummy variable GRaster
layers for use with models that have factors, especially if the input GRaster
is categorical. Note that the predict()
function in fasterRaster usually does not need this treatment of GRaster
s since it can handle categorical rasters already.
Usage
## S4 method for signature 'GRaster'
segregate(x, classes = NULL, keep = FALSE, other = 0, bins = 100, digits = 3)
Arguments
x |
A |
classes |
Either |
keep |
Logical: If |
other |
Numeric or |
bins |
Numeric: Number of bins in which to put values. This is only used for |
digits |
Numeric: Number of digits to which to round input if it is a |
Value
If the input x
is a single-layered GRaster
, the output will be a multi-layered GRaster
with one layer per value in the input, or one layer per values in classes
. If the input is a multi-layered GRaster
, the output will be a list
of multi-layered GRaster
s.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation and land cover raster
madElev <- fastData("madElev") # integer raster
madCover <- fastData("madCover") # categorical raster
# Convert to GRasters
elev <- fast(madElev)
cover <- fast(madCover)
# Subset elevation raster to just a few values to make example faster:
elevSubset <- elev[elev <= 3]
segregate(elevSubset)
segregate(elevSubset, keep = TRUE, other = -1)
# Segregate the factor raster
segregate(cover)
classes <- c("Grassland with mosaic forest", "Mosaic cropland/vegetation")
seg <- segregate(cover, classes = classes)
plot(seg)
}
Select values from rasters in a stack based on values in another raster
Description
selectRange()
selects values from GRaster
s in a "stack" based on the values in another "selection" raster. For example, if the stack has three layers (call them A, B, and C), the "selection" raster could have values of 1, 2, or 3 in each cell. The raster that is returned will have values from A wherever the selection raster is 1, B from where it is 2, and C from where it is 3.
Usage
## S4 method for signature 'GRaster'
selectRange(x, y)
Arguments
x |
A |
y |
A |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
# Make a stack of various versions of "elev" from which to select from:
x <- c(elev, 10 * elev, ln(elev), -1 * elev)
x
# Make a layer with random numbers between 1 and 4:
fun <- "= round(rand(0.5, 4.5))"
y <- app(elev, fun = fun)
selected <- selectRange(x, y)
}
Format a numeric series into an SQL value call
Description
This function takes as its argument a vector of integers or numeric values, and converts sequential runs to a range while keeping non-sequential values as-is. For example, c(1, 5, 6, 7, 8, 9, 15, 16, 20)
becomes "1,5-9,15-16,20"
. This reduces the number of characters necessary to supply to a SQL condition. This function is mainly of use to developers.
Usage
seqToSQL(x, maxChar = 29900, sort = TRUE)
Arguments
x |
A vector of numerical values. The vector should be sorted from lowers to highest for the most efficient "compression" of sequential ranges. Values will be coerced to class |
maxChar |
Integer or numeric: Maximum number of characters to include in the output. If the output has more than this number of characters, the remainder is dropped, and the |
sort |
Logical: If |
Value
A character string. The string has three attributes. The trim
attribute is TRUE
or FALSE
, depending on whether maxChar
was reached or not (and subsequent numbers dropped from the string). The lastIndex
attribute is the last index of x
that was processed (i.e., the index of the last value in the output), and the number of values represented by the output.
Examples
x <- 1:5
seqToSQL(x)
x <- c(1:5, 7)
seqToSQL(x)
x <- c(1:5, 7, 15:16)
y <- c(1:5, 7, 15:16, 20)
seqToSQL(x)
seqToSQL(y)
seqToSQL(x, maxChar = 5)
seqToSQL(y, maxChar = 8)
seqToSQL(10:1, sort = FALSE)
seqToSQL(10:1, sort = TRUE)
Simplify the geometry of a vector
Description
simplifyGeom()
reduces the number of vertices used to represent a vector (i.e., to save memory or disk space). There are several methods available.
Usage
## S4 method for signature 'GVector'
simplifyGeom(x, tolerance = NULL, method = "VR", prop = 0.5)
Arguments
x |
A |
tolerance |
Numeric >= 0: Threshold distance in map units (degrees for unprojected, usually meters for projected). If |
method |
Character: Method used to reduce the number of vertices. Partial matching is used, and case does not matter:
|
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). |
Value
A GVector
.
See Also
smoothGeom()
, geometry cleaning, terra::simplifyGeom()
, GRASS manual page for tool v.generalize
(see grassHelp("v.generalize")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madRivers <- fastData("madRivers")
rivers <- fast(madRivers)
soam <- rivers[rivers$NAM == "SOAMIANINA"] # select one river for illustration
### Simplify geometry (remove nodes)
vr <- simplifyGeom(soam, tolerance = 2000)
dp <- simplifyGeom(soam, tolerance = 2000, method = "dp")
dpr <- simplifyGeom(soam, tolerance = 2000, method = "dpr", prop = 0.5)
rw <- simplifyGeom(soam, tolerance = 2000, method = "rw")
plot(soam, col = "black", lwd = 3)
plot(vr, col = "blue", add = TRUE)
plot(dp, col = "red", add = TRUE)
plot(dpr, col = "chartreuse", add = TRUE)
plot(rw, col = "orange", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Vertex reduction",
"Douglas-Peucker",
"Douglas-Peucker reduction",
"Reumann-Witkam"
),
col = c("black", "blue", "red", "chartreuse", "orange"),
lwd = c(3, 1, 1, 1, 1)
)
### Smooth geometry
hermite <- smoothGeom(soam, dist = 2000, angle = 3)
chaiken <- smoothGeom(soam, method = "Chaiken", dist = 2000)
plot(soam, col = "black", lwd = 2)
plot(hermite, col = "blue", add = TRUE)
plot(chaiken, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Hermite",
"Chaiken"
),
col = c("black", "blue", "red"),
lwd = c(2, 1, 1, 1, 1)
)
### Clean geometry
# Has no effect on this vector!
noDangs <- removeDangles(soam, tolerance = 10000)
plot(soam, col = "black", lwd = 2)
plot(noDangs, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"No dangles"
),
lwd = c(2, 1),
col = c("black", "red")
)
}
Sine wave rasters
Description
This function creates one or more rasters with sine waves in the north-south and east-west directions.
Usage
## S4 method for signature 'GRaster'
sineRast(
x,
ns = 1,
ew = 1,
nsOffset = 0,
ewOffset = 0,
nsAmp = 1,
ewAmp = 1,
combos = FALSE,
mask = NULL,
verbose = FALSE
)
Arguments
x |
A |
ns , ew |
Numeric: Number of complete sine waves (i.e., wavelengths) in the north-south and east-west directions. A wavelength of 1 creates a "full" sine wave (e.g., starting at 0 at one end and ending at 0 at the other). A wavelength of 2 would create two such waves, and so on. A value of 0 creates no waves in the given direction (i.e., each row or column has constant values). The default value is 1. |
nsOffset , ewOffset |
Numeric: Offset of the sine waves from the edges of the raster, expressed as a proportion of the length of the raster. The default is 0, so the values of the outermost cells will be close to 0 (but not exactly 0 because centers of cells at the raster edges are not on the actual edge). If an offset value is 0.2, for example, then it will be pushed "inward" toward the middle of the raster by 20% of the raster's extent. |
nsAmp , ewAmp |
Numeric: Amplitude (minimum and maximum of the sine wave) in the north-south and east-west directions. The default is 1. Note that when north-south and east-west waves are created (i.e., |
combos |
Logical: If |
mask |
Either |
verbose |
Logical: If |
Value
A GRaster
.
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert to GRaster:
elev <- fast(madElev)
### Simple sine waves:
waves <- sineRast(elev, ns = 2, ew = 1)
plot(waves)
### Sine waves with different amplitudes:
amps <- sineRast(elev, nsAmp = c(1, 5), ewAmp = c(1, 5))
amps
### Sine waves with and without north-south offset:
noOffsets <- sineRast(elev, ns = 1, ew = 1)
offsets <- sineRast(elev, ns = 1, ew = 1, nsOffset = 0.25)
offs <- c(noOffsets, offsets)
names(offs) <- c("no offset", "offset")
plot(offs)
### Masking:
madCoast4 <- fastData("madCoast4")
coast4 <- fast(madCoast4, verbose = FALSE)
masked <- sineRast(elev, mask = coast4)
plot(masked)
### Multiple sine waves (multiple rasters):
mults <- sineRast(elev, ns = 1:2, ew = 1:2)
combos <- sineRast(elev, ns = 1:2, ew = 1:2, combos = TRUE)
plot(mults)
plot(combos)
}
Smooth the geometry of a vector
Description
smoothGeom()
makes line segments of a vector appear less angular.
Usage
## S4 method for signature 'GVector'
smoothGeom(x, method = "Hermite", dist = NULL, angle = 3)
Arguments
x |
A |
method |
Character: Method used to smooth line segments. Partial matching is used, and case does not matter:
|
dist |
Numeric > 0 of |
angle |
Numeric > 0: Maximum angle for the Hermite algorithm. Default is 3. |
Value
A GVector
.
See Also
simplifyGeom()
, terra::simplifyGeom()
, geometry cleaning, GRASS manual page for tool v.generalize
(see grassHelp("v.generalize")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madRivers <- fastData("madRivers")
rivers <- fast(madRivers)
soam <- rivers[rivers$NAM == "SOAMIANINA"] # select one river for illustration
### Simplify geometry (remove nodes)
vr <- simplifyGeom(soam, tolerance = 2000)
dp <- simplifyGeom(soam, tolerance = 2000, method = "dp")
dpr <- simplifyGeom(soam, tolerance = 2000, method = "dpr", prop = 0.5)
rw <- simplifyGeom(soam, tolerance = 2000, method = "rw")
plot(soam, col = "black", lwd = 3)
plot(vr, col = "blue", add = TRUE)
plot(dp, col = "red", add = TRUE)
plot(dpr, col = "chartreuse", add = TRUE)
plot(rw, col = "orange", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Vertex reduction",
"Douglas-Peucker",
"Douglas-Peucker reduction",
"Reumann-Witkam"
),
col = c("black", "blue", "red", "chartreuse", "orange"),
lwd = c(3, 1, 1, 1, 1)
)
### Smooth geometry
hermite <- smoothGeom(soam, dist = 2000, angle = 3)
chaiken <- smoothGeom(soam, method = "Chaiken", dist = 2000)
plot(soam, col = "black", lwd = 2)
plot(hermite, col = "blue", add = TRUE)
plot(chaiken, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"Hermite",
"Chaiken"
),
col = c("black", "blue", "red"),
lwd = c(2, 1, 1, 1, 1)
)
### Clean geometry
# Has no effect on this vector!
noDangs <- removeDangles(soam, tolerance = 10000)
plot(soam, col = "black", lwd = 2)
plot(noDangs, col = "red", add = TRUE)
legend("bottom",
xpd = NA,
legend = c(
"Original",
"No dangles"
),
lwd = c(2, 1),
col = c("black", "red")
)
}
Name of a raster or vector in a GRASS session
Description
sources()
retrieves the name of a raster or vector in GRASS. GRaster
s and GVector
s are actually pointers to objects stored in a GRASS database. When using fasterRaster functions on rasters and vectors, the commands are translated into GRASS commands and executed on the objects named in the pointers. These objects use a "source" (which is really a filename) to refer to the GRASS objects. This function is mostly of use to developers.
Usage
## S4 method for signature 'GRaster'
sources(x)
## S4 method for signature 'GVector'
sources(x)
## S4 method for signature 'character'
sources(x)
Arguments
x |
Either a |
Value
Character.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Sample random points from a GRaster or GVector
Description
spatSample()
randomly locates points across a GRaster
or GVector
. It can return a GVector
, the coordinates, values associated with the points, or all of these. If you want to generate a raster with randomly-sampled cells, see sampleRast()
.
Usage
## S4 method for signature 'GRaster'
spatSample(
x,
size,
as.points = FALSE,
values = TRUE,
cats = TRUE,
xy = FALSE,
strata = NULL,
byStratum = FALSE,
zlim = NULL,
seed = NULL,
verbose = FALSE
)
## S4 method for signature 'GVector'
spatSample(
x,
size,
as.points = FALSE,
values = TRUE,
xy = FALSE,
byStratum = FALSE,
zlim = NULL,
seed = NULL
)
Arguments
x |
A |
size |
Numeric value > 0: Number of points to create. |
as.points |
Logical: If |
values |
Logical: If |
cats |
Logical: If |
xy |
Logical: If |
strata |
Either |
byStratum |
Logical: If |
zlim |
Either |
seed |
Either |
verbose |
Logical: If |
Value
A data.frame
, data.table
, or GVector
.
See Also
sampleRast()
, terra::spatSample()
, tool v.random
in GRASS (see grassHelp("v.random")
)
Examples
if (grassStarted()) {
# Setup
library(sf)
library(terra)
# Example data
madElev <- fastData("madElev") # raster
# Convert to GRasters and GVectors
elev <- fast(madElev)
### spatSample()
# Random points as data.frame or data.table:
randVals <- spatSample(elev, size = 20, values = TRUE)
randVals
# Random points as a points GVector:
randPoints <- spatSample(elev, size = 20, as.points = TRUE)
randPoints
plot(elev)
plot(randPoints, add = TRUE)
# Random points in a select area:
madCoast <- fastData("madCoast4") # vector
coast <- fast(madCoast)
ant <- coast[coast$NAME_4 == "Antanambe"] # subset
restrictedPoints <- spatSample(elev, size = 20, as.points = TRUE,
strata = ant)
plot(elev)
plot(ant, add = TRUE)
plot(restrictedPoints, add = TRUE) # note 20 points for entire geometry
# Random points, one set per subgeometry:
stratifiedPoints <- spatSample(elev, size = 20, as.points = TRUE,
strata = ant, byStratum = TRUE)
plot(elev)
plot(ant, add = TRUE)
plot(stratifiedPoints, pch = 21, bg = "red", add = TRUE) # note 20 points per subgeometry
# Random categories:
madCover <- fastData("madCover") # raster
cover <- fast(madCover)
randCover <- spatSample(cover, size = 20, values = TRUE,
cat = TRUE, xy = TRUE)
randCover
### sampleRast()
# Random cells in non-NA cells:
rand <- sampleRast(elev, 10000)
plot(rand)
nonnacell(rand)
# Use custom values for the mask:
randCustomMask <- sampleRast(elev, 10000, maskvalues = 1:20)
plot(randCustomMask)
# Force selected values to a custom value:
randCustomUpdate <- sampleRast(elev, 10000, updatevalue = 7)
plot(randCustomUpdate)
# Custom values for mask and set selected cells to custom value:
randAll <- sampleRast(elev, 10000, maskvalues = 1:20, updatevalue = 7)
plot(randAll)
}
Create stream network
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")
)
Usage
## S4 method for signature 'GRaster'
streams(
x,
accumulation = NULL,
depression = NULL,
flowThreshold = 1,
dirThreshold = 1,
montgomery = 0,
minLength = 1
)
Arguments
x |
A |
accumulation |
Either |
depression |
Either |
flowThreshold |
Numeric > 0: Minimum threshold for a stream to be generated. The default is 1, which is not necessarily a reasonable value. |
dirThreshold |
Numeric (default is |
montgomery |
Numeric: The "Montgomery" exponent for slope, multiplied by accumulation as per |
minLength |
Numeric: First-order streams less than this length are removed (units in cells). Default is 0 (no removal). |
Value
A GRaster
.
See Also
flow()
, flowPath()
, GRASS manual for tool r.stream.extract
(see grassHelp("r.stream.extract")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
# Calculate stream channels
streams <- streams(elev)
plot(streams)
}
Rescale values in a GRaster
Description
stretch()
rescales the values in a GRaster
. All values can be rescaled, or just values in a user-defined range. This range can be given by specifying either the lower and upper bounds of the range using smin
and smax
, and/or by the quantiles (across all cells of the raster) using minq
and maxq
.
Usage
## S4 method for signature 'GRaster'
stretch(x, minv = 0, maxv = 255, minq = 0, maxq = 1, smin = NA, smax = NA)
Arguments
x |
A |
minv , maxv |
Numeric: Minimum and maximum values to which to rescale values. |
minq , maxq |
Numeric: Specifies range of values to rescale, given by their quantiles. The default is to stretch all values (the 0th and 100th quantiles). One or both are ignored if |
smin , smax |
Numeric or |
Value
A GRaster
.
See Also
terra::stretch()
and tool r.rescale
in GRASS (not used on this function)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
### Stretch based on user-defined range
# fasterRaster
fr <- stretch(elev, smin=1, smax=100)
fr
# terra
tr <- stretch(madElev, smin = 1, smax = 100)
tr
# Compare fasterRaster to terra output
fr <- rast(fr)
fr <- extend(fr, tr)
fr - tr
### Stretch values in a certain quantile range
# fasterRaster
fr <- stretch(elev, minq = 0.25, maxq = 0.75)
fr
# terra
tr <- stretch(madElev, minq = 0.25, maxq = 0.75)
tr
# Compare fasterRaster to terra output
fr <- rast(fr)
fr <- extend(fr, tr)
fr - tr
}
Subset layers from a GRaster, or specific rows from a GVector
Description
subset()
can be used to subset or remove one or more layers from a GRaster
. It can also be used to subset or remove rows from a GVector
with a data table.
Usage
## S4 method for signature 'GRaster'
subset(x, subset, negate = FALSE)
## S4 method for signature 'GVector'
subset(x, subset, negate = FALSE)
Arguments
x |
A |
subset |
Numeric integer, integer, logical, or character: Indicates the layer(s) of a |
negate |
Logical: If |
Value
A GRaster
or GVector
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
### GRasters
# Example data
madElev <- fastData("madElev") # elevation raster
madForest2000 <- fastData("madForest2000") # forest raster
madForest2014 <- fastData("madForest2014") # forest raster
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
forest2014 <- fast(madForest2014)
# Re-assigning values of a GRaster
constant <- elev
constant[] <- pi
names(constant) <- "pi_raster"
constant
# Re-assigning specific values of a raster
replace <- elev
replace[replace == 1] <- -20
replace
# Subsetting specific values of a raster based on another raster
elevInForest <- elev[forest2000 == 1]
plot(c(elev, forest2000, elevInForest), nr = 1)
# Adding and replacing layers of a GRaster
rasts <- c(elev, constant, forest2000)
# Combine with another layer:
add(rasts) <- forest2014 # one way
rasts
rasts <- c(rasts, forest2014) # another way
### Subsetting GRaster layers
# Subset:
rasts <- c(elev, forest2000, forest2014)
rasts[[2:3]]
subset(rasts, 2:3)
subset(rasts, c("madForest2000", "madElev"))
rasts[[c("madForest2000", "madElev")]]
rasts$madForest2000
# Get every other layer:
rasts[[c(FALSE, TRUE)]]
### Replacing layers of a GRaster
# Replace a layer
logElev <- log(elev)
names(logElev) <- "logElev"
rasts$madForest2014 <- logElev
rasts
# Replace a layer:
rasts[[3]] <- forest2000
rasts
### GVectors
# example data
madDypsis <- fastData("madDypsis") # vector of points
madDypsis <- vect(madDypsis)
# Convert SpatVector to GVector
dypsis <- fast(madDypsis)
### Retrieving GVector columns
dypsis$species # Returns the column
dypsis[[c("year", "species")]] # Returns a GVector with these columns
dypsis[ , c("year", "species")] # Same as above
### Subsetting GVector geometries
# 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"]
### (Re)assigning GVector column values
# New column
dypsis$pi <- pi
head(dypsis)
# Re-assign values
dypsis$pi <- "pie"
head(dypsis)
# Re-assign specific values
dypsis$institutionCode[dypsis$institutionCode == "MO"] <-
"Missouri Botanical Garden"
}
Replace a specific value(s) in a GRaster
Description
This function replaces one or more user-specified values in a raster with other values. See classify()
for replacing ranges of values.
Usage
## S4 method for signature 'GRaster'
subst(x, from, to, others = NULL, warn = TRUE)
Arguments
x |
A |
from , to |
Vectors of numeric or character values. The value(s) in
|
others |
|
warn |
Logical: If |
Value
A GRaster
.
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madCover <- fastData("madCover")
### Substitution within an integer/numeric raster
# Convert SpatRaster to GRaster
elev <- fast(madElev)
# Simple substitution of one value, keeping all other values
newElev <- elev
newElev[newElev == 100] <- -100
newElev[newElev > 500] <- 500
hist(newElev)
# Simple substitution of one value, keeping all other values
substituted <- subst(elev, from = 300, to = -300)
substituteds <- c(elev, substituted)
names(substituteds) <- c("original", "substituted")
plot(substituteds)
# Simple substitution of three values, keeping all other values
substituted <- subst(elev, from = c(299, 300, 301), to = c(-699, -600, -601))
substituteds <- c(elev, substituted)
names(substituteds) <- c("original", "substituted")
plot(substituteds)
# Simple substitution of three values to one other value, retaining remainder
substituted <- subst(elev, from = c(299, 300, 301), to = -1000)
substituteds <- c(elev, substituted)
names(substituteds) <- c("original", "substituted")
plot(substituteds)
# Simple substitution of one value, setting all other values to 100
substituted <- subst(elev, from = 300, to = -300, others = 100)
substituteds <- c(elev, substituted)
names(substituteds) <- c("original", "substituted")
plot(substituteds)
### Substitution within a factor/categorical raster
# Convert a SpatRaster to a GRaster:
cover <- fast(madCover)
cover <- droplevels(cover) # remove unused levels
levels(cover) # levels of "cover"
# Substitute using level name, replace with EXISTING level label
from <- "Mosaic cropland/vegetation"
to <- "Mosaic crops"
categ <- subst(cover, from = from, to = to)
freq(cover) # original frequencies of each land cover class
freq(categ) # note change in frequency of "from" and "to" categories
plot(c(cover, categ))
# Substitute using level name, replace with NEW level label
from <- c("Mosaic crops", "Mosaic cropland/vegetation")
to <- c("Mixed cropland")
categ <- subst(cover, from = from, to = to)
freq(cover) # original frequencies of each land cover class
freq(categ) # note change in frequency of "from" and "to" categories
plot(c(cover, categ))
# Substitute using level name, replace with NEW level label
from <- c("Mosaic crops", "Mosaic cropland/vegetation")
to <- c("Mixed cropland", "Mixed cropland/vegetation")
categ <- subst(cover, from = from, to = to)
freq(cover) # original frequencies of each land cover class
freq(categ) # note change in frequency of "from" and "to" categories
plot(c(cover, categ))
# Substitute using level name, replace with VALUE of an existing label
from <- c("Mosaic crops", "Mosaic cropland/vegetation")
to <- 120
categ <- subst(cover, from = from, to = to)
freq(cover) # original frequencies of each land cover class
freq(categ) # note change in frequency of "from" and "to" categories
plot(c(cover, categ))
# Substitute using level name, replace with new level name, replace all others
from <- c("Mosaic crops", "Mosaic cropland/vegetation")
to <- "Crops"
categ <- subst(cover, from = from, to = to, others = "Other")
freq(cover) # original frequencies of each land cover class
freq(categ) # note change in frequency of "from" and "to" categories
plot(c(cover, categ))
}
Solar radiance and irradiance
Description
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")
)
Usage
sun(
elevation,
coeff_bh,
coeff_dh,
slope,
aspect,
hh,
horizon_step = 90,
albedo = 0.2,
linke = 3,
day = 1,
step = 0.5,
declination = NULL,
solar_constant = 1367,
distance_step = 1,
npartitions = 1,
beam_rad = TRUE,
diff_rad = TRUE,
refl_rad = TRUE,
glob_rad = TRUE,
insol_time = TRUE,
lowMemory = FALSE
)
Arguments
elevation |
A |
coeff_bh |
A |
coeff_dh |
A |
slope |
A |
aspect |
A |
hh |
A "stack" of |
horizon_step |
Numeric >0: Difference between angular steps in which horizon height is measured. One horizon height raster will be made per value from 0 to 360 - |
albedo |
A |
linke |
A |
day |
Positive integer between 1 to 365, inclusive: Day of year for which to calculate ir/radiation. Default is 1 (January 1st). |
step |
Positive integer between 0 and 24, inclusive. Time step in hours for all-day radiation sums. Decimal values are OK. |
declination |
Numeric or |
solar_constant |
Positive numeric: The solar constant (solar energy hitting the top of the atmosphere). Default is 1367. Units are W / m^2. |
distance_step |
Positive numeric between 0.5 and 1.5, inclusive: Sampling distance coefficient. Default is 1. |
npartitions |
Positive numeric. Number of chunks in which to read input files. Default is 1. |
beam_rad |
Logical: If |
diff_rad |
Logical: If |
refl_rad |
Logical: If |
glob_rad |
Logical:. If |
insol_time |
Logical: If |
lowMemory |
Logical: If |
Value
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) -
diff_rad
: Diffuse radiation (Watt-hours/m2/day) -
refl_rad
: Reflected radiation (Watt-hours/m2/day) -
glob_rad
: Global radiation (Watt-hours/m2/day) -
insol_time
: Insolation duration (hours)
See Also
terrain()
, horizonHeight()
, GRASS manual page for tool r.sun
(see grassHelp("r.sun")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
### Calculate input rasters
# Values below are just a guess
coeff_bh <- coeff_dh <- elev
coeff_bh[] <- 0.4
coeff_dh[] <- 0.6
slope <- terrain(elev, "slope")
aspect <- terrain(elev, "aspect", northIs0 = FALSE)
horizon_step <- 90
hh <- horizonHeight(elev, step = horizon_step, northIs0 = FALSE)
### calculate solar ir/radiance
solar <- sun(
elevation = elev,
coeff_bh = coeff_bh,
coeff_dh = coeff_dh,
slope = slope,
aspect = aspect,
hh = hh,
horizon_step = horizon_step,
albedo = 0.2,
linke = 1.5,
day = 1,
step = 0.5,
declination = NULL,
solar_constant = 1367,
distance_step = 1,
npartitions = 1,
beam_rad = TRUE,
diff_rad = TRUE,
refl_rad = TRUE,
glob_rad = TRUE,
insol_time = TRUE,
lowMemory = FALSE
)
solar
}
Slope, aspect, curvature, and partial slopes
Description
terrain()
calculates topographic indices, including slope, aspect, curvature, and partial slopes (slopes in the east-west or north-south directions).
Usage
## S4 method for signature 'GRaster'
terrain(
x,
v = "slope",
units = "degrees",
undefinedAspect = NA,
northIs0 = TRUE
)
Arguments
x |
A |
v |
Name of the topographic metric(s) to calculate. Valid values include one or more of:
|
units |
Character: "Units" in which to calculate slope and aspect: either |
undefinedAspect |
Numeric or |
northIs0 |
Logical: If |
Value
A GRaster
with one or more layers.
See Also
terra::terrain()
, ruggedness()
, wetness()
, geomorphons()
, tool r.slope.aspect
in GRASS
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster
elev <- fast(madElev)
# Calculate all topographic metrics
topos <- terrain(elev, v = "*")
topos
plot(topos) # NB Aspect has values of NA when it cannot be defined
# Calculate a hillshade raster
hs <- hillshade(elev)
plot(hs)
}
Reduce linear features on a raster so linear features are 1 cell wide
Description
The thinLines()
function attempts to reduce linear features on a raster to just 1 cell wide. You may need to run thinLines()
multiple times on the same raster (or experiment with the iter
argument) to get acceptable output. thinLines()
can be helpful to run on a raster before using as.lines()
.
Usage
## S4 method for signature 'GRaster'
thinLines(x, iter = 200)
Arguments
x |
A |
iter |
Numeric integer: Number of iterations (default is 200). |
Value
A GRaster
.
See Also
as.lines()
, GRASS manual page for tool r.thin
(see grassHelp("r.thin")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation
madElev <- fastData("madElev")
# Convert to GRaster:
elev <- fast(madElev)
# Thin elevation raster:
thinned <- thinLines(elev, iter = 300)
plot(thinned)
# Convert to lines:
rastToLines <- as.lines(thinned)
plot(rastToLines)
# We can clean this:
cleanLines <- fixDangles(x = rastToLines)
plot(rastToLines, col = "red")
plot(cleanLines, add = TRUE)
}
Reduce number of points in same raster cell
Description
This function thins a "points" GVector
so that it has no more than n
points per grid cell in a raster.
Usage
## S4 method for signature 'GVector,GRaster'
thinPoints(x, y, n = 1)
Arguments
x |
A "points" |
y |
A |
n |
Integer or numeric integer: Maximum number of points to remain in a cell. The default is 1. |
Value
A "points" GVector
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation and points
madElev <- fastData("madElev")
madDypsis <- fastData("madDypsis")
# Convert to fasterRaster formats:
elev <- fast(madElev)
dypsis <- fast(madDypsis)
# Aggregate cells of the raster so they are bigger
elevAgg <- aggregate(elev, 32)
# Remove all but one or two points per cell
thin1 <- thinPoints(dypsis, elevAgg, n = 1)
thin2 <- thinPoints(dypsis, elevAgg, n = 2)
# Plot
plot(elevAgg)
plot(dypsis, add = TRUE)
plot(thin2, col = "yellow", add = TRUE)
plot(thin1, col = "red", add = TRUE)
legend(
"bottomright",
legend = c("In original & thin 1 & 2",
"In just thin 1 & 2", "In just thin 1"),
pch = 16,
col = c("black", "yellow", "red"),
bg = "white",
xpd = NA
)
}
Divide a GRaster into spatially exclusive subsets
Description
This function divides a GRaster
into "tiles" or spatial subsets which can be used for speeding some raster calculations. Tiles can be mutually exclusive or overlap by a user-defined number of cells.
Usage
## S4 method for signature 'GRaster'
tiles(x, n, overlap = 0, verbose = FALSE)
Arguments
x |
A |
n |
Numeric vector: Number of tiles to create. This can be a single number, in which case |
overlap |
Numeric vector (default is 0): Number of rows/columns by which to expand the size of tiles so they overlap. This can be a single value or two values. If just one is provided, the tiles will be expanded by |
verbose |
Logical: If |
Value
If x
has just one layer, then the output is a list
with one element per tile. The lapply()
and sapply()
functions can be used to apply functions to each tile in the list. If x
has more than one layer, then the output will be a list
of list
s, with each sub-list
containing the tiles for one GRaster
layer.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Create spatially exclusive tiles:
exclusive <- tiles(elev, n = 2, verbose = TRUE)
startpar <- par(mfrow = c(2, 3))
plot(elev, main = "Original")
for (i in seq_along(exclusive)) {
plot(exclusive[[i]], ext = elev, main = paste("Tile", i))
}
par(startpar)
# Create tiles that overlap:
overlaps <- tiles(elev, n = 2, overlap = 200, verbose = TRUE)
startpar <- par(mfrow = c(2, 3))
plot(elev, main = "Original")
for (i in seq_along(overlaps)) {
plot(overlaps[[i]], ext = elev, main = paste("Tile", i))
}
par(startpar)
}
Topology (2- or 3-dimensions) of a GRaster or GVector
Description
GRaster
s and GVector
s can have 2-dimensional or 3-dimensional coordinates. This function returns the dimensions of the object.
Usage
## S4 method for signature 'GSpatial'
topology(x)
Arguments
x |
A |
Value
Either "2D" or "3D".
See Also
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Remove rows and columns from a raster that are all NA
Description
This function removes any rows and columns from a GRaster
that are all NA
.
If the GRaster
is a stack of rasters, then the rasters will all be trimmed to the same extent such that none have any rows or columns that are all NA
. In other words, if at least one raster in the stack has a non-NA
cell in a row or column, all rasters will retain that row or column.
Usage
## S4 method for signature 'GRaster'
trim(x, pad = 0)
Arguments
x |
A |
pad |
Numeric integer: Number of |
Value
A GRaster
.
See Also
terra::trim()
, extend()
, and GRASS tool g.region
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert SpatRaster to a GRaster:
elev <- fast(madElev)
# Trim NA rows/columns:
trimmedElev <- trim(elev)
dim(elev)
dim(trimmedElev)
# Trim a "stack" of rasters. We will artificially add NA rows and columns to
# one raster to demonstrate how the trim() function removes only rows/columns
# that are NA for *all* rasters.
elevNAs <- elev
fun <- " = if(col() > ncols() - 200, null(), madElev)"
elevNAs <- app(elevNAs, fun)
# Notice raster is "narrower" because we added NA columns
plot(elevNAs)
elevs <- c(elev, elevNAs)
trimmedElevs <- trim(elevs)
trimmedElevNAs <- trim(elevNAs)
dim(elevs)
dim(trimmedElevNAs)
dim(trimmedElevs)
}
Combine two GVectors
Description
The union()
function combines two "polygons" GVector
s. The output will have at least as many geometries as both GVector
s, plus more if polygons of one divide polygons of the other, and vice versa. You can also use the +
operator (e.g., vect1 + vect2
).
Usage
## S4 method for signature 'GVector,GVector'
union(x, y)
Arguments
x , y |
|
Value
A GVector
.
See Also
c()
, aggregate()
, crop()
, intersect()
, xor()
, erase()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Polygon of coastal Madagascar and Dypsis specimens
madCoast4 <- fastData("madCoast4") # polygons
madDypsis <- fastData("madDypsis") # points
# Convert vectors:
coast4 <- fast(madCoast4)
dypsis <- fast(madDypsis)
# Create another polygons vector from a convex hull around Dypsis points
hull <- convHull(dypsis)
### union()
unioned <- union(coast4, hull)
plot(unioned)
plus <- coast4 + hull # same as union()
### intersect
inter <- intersect(coast4, hull)
plot(coast4)
plot(hull, border = "red", add = TRUE)
plot(inter, border = "blue", add = TRUE)
### xor
xr <- xor(coast4, hull)
plot(coast4)
plot(xr, border = "blue", add = TRUE)
### erase
erased <- erase(coast4, hull)
plot(coast4)
plot(erased, border = "blue", add = TRUE)
minus <- coast4 - hull # same as erase()
}
Refresh metadata in a GRaster or GVector
Description
GRaster
s and GVector
s are really pointers to objects in GRASS. The values displayed when you use show()
or print()
for a GRaster
or GVector
are stored in R. If, on the odd chance that you make a change to a GRaster
or GVector
(e.g., using commands in the rgrass package), the changes will not be automatically reflected in the GRaster
or GVector
. This function can be used to update the objects in R to reflect their proper values.
Usage
## S4 method for signature 'GRaster'
update(object)
## S4 method for signature 'GVector'
update(object)
Arguments
object |
A |
Value
A GRaster
or GVector
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
# Convert SpatRasters to GRasters
elev <- fast(madElev)
forest <- fast(madForest2000)
### GRaster properties
# plotting
plot(elev)
# dimensions
dim(elev) # rows, columns, depths, layers
nrow(elev) # rows
ncol(elev) # columns
ndepth(elev) # depths
nlyr(elev) # layers
res(elev) # resolution (2D)
res3d(elev) # resolution (3D)
zres(elev) # vertical resolution
xres(elev) # vertical resolution
yres(elev) # vertical resolution
zres(elev) # vertical resolution (NA because this is a 2D GRaster)
# cell counts
ncell(elev) # cells
ncell3d(elev) # cells (3D rasters only)
# number of NA and non-NA cells
nacell(elev)
nonnacell(elev)
# topology
topology(elev) # number of dimensions
is.2d(elev) # is it 2-dimensional?
is.3d(elev) # is it 3-dimensional?
minmax(elev) # min/max values
# "names" of the object
names(elev)
# coordinate reference system
crs(elev)
st_crs(elev)
coordRef(elev)
# extent (bounding box)
ext(elev)
# vertical extent (not defined for this raster)
zext(elev)
# data type
datatype(elev) # fasterRaster type
datatype(elev, "GRASS") # GRASS type
datatype(elev, "terra") # terra type
datatype(elev, "GDAL") # GDAL type
is.integer(elev)
is.float(elev)
is.double(elev)
is.factor(elev)
# convert data type
as.int(elev) # integer; note that "elev" is already of type "integer"
as.float(elev) # floating-precision
as.doub(elev) # double-precision
# assigning
pie <- elev
pie[] <- pi # assign all cells to the value of pi
pie
# concatenating multiple GRasters
rasts <- c(elev, forest)
rasts
# subsetting
rasts[[1]]
rasts[["madForest2000"]]
# replacing
rasts[[2]] <- 2 * forest
rasts
# adding layers
rasts[[3]] <- elev > 500 # add a layer
rasts <- c(rasts, sqrt(elev)) # add another
add(rasts) <- ln(elev)
rasts
# names
names(rasts)
names(rasts) <- c("elev_meters", "2_x_forest", "high_elevation", "sqrt_elev", "ln_elev")
rasts
# remove a layer
rasts[["2_x_forest"]] <- NULL
rasts
# number of layers
nlyr(rasts)
# correlation and covariance matrices
madLANDSAT <- fastData("madLANDSAT")
landsat <- fast(madLANDSAT) # projects matrix
layerCor(landsat) # correlation
layerCor(landsat, fun = 'cov') # covariance
}
Convert a GVector to a SpatVector or sf vector
Description
The fasterRaster version of the vect()
function converts a GVector
to a SpatVector
(from the terra package). The fasterRaster version of the st_as_sf()
function converts a GVector
to an sf
object (sf package).
Usage
## S4 method for signature 'GVector'
vect(x, ...)
## S4 method for signature 'GVector'
st_as_sf(x)
Arguments
x |
A |
... |
Additional arguments to send to |
Value
vect()
returns a SpatVector
(terra package), and st_as_sf()
returns an sf
vector (sf package).
See Also
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example data:
madCoast4 <- fastData("madCoast4")
madRivers <- fastData("madRivers")
madDypsis <- fastData("madDypsis")
# Convert sf vectors to GVectors:
coast <- fast(madCoast4)
rivers <- fast(madRivers)
dypsis <- fast(madDypsis)
# Geographic properties:
ext(rivers) # extent
crs(rivers) # coordinate reference system
st_crs(rivers) # coordinate reference system
coordRef(rivers) # coordinate reference system
# Column names and data types:
names(coast)
datatype(coast)
# Points, lines, or polygons?
geomtype(dypsis)
geomtype(rivers)
geomtype(coast)
is.points(dypsis)
is.points(coast)
is.lines(rivers)
is.lines(dypsis)
is.polygons(coast)
is.polygons(dypsis)
# Number of dimensions:
topology(rivers)
is.2d(rivers) # 2-dimensional?
is.3d(rivers) # 3-dimensional?
# Just the data table:
as.data.frame(rivers)
as.data.table(rivers)
# Top/bottom of the data table:
head(rivers)
tail(rivers)
# Vector or table with just selected columns:
names(rivers)
rivers$NAME
rivers[[c("NAM", "NAME_0")]]
rivers[[c(3, 5)]]
# Select geometries/rows of the vector:
nrow(rivers)
selected <- rivers[2:6]
nrow(selected)
# Plot:
plot(coast)
plot(rivers, col = "blue", add = TRUE)
plot(selected, col = "red", lwd = 2, add = TRUE)
# Vector math:
hull <- convHull(dypsis)
un <- union(coast, hull)
sameAsUnion <- coast + hull
plot(un)
plot(sameAsUnion)
inter <- intersect(coast, hull)
sameAsIntersect <- coast * hull
plot(inter)
plot(sameAsIntersect)
er <- erase(coast, hull)
sameAsErase <- coast - hull
plot(er)
plot(sameAsErase)
xr <- xor(coast, hull)
sameAsXor <- coast / hull
plot(xr)
plot(sameAsXor)
# Vector area and length:
expanse(coast, unit = "km") # polygons areas
expanse(rivers, unit = "km") # river lengths
### Fill holes
# First, we will make some holes by creating buffers around points.
buffs <- buffer(dypsis, 500)
holes <- coast - buffs
plot(holes)
filled <- fillHoles(holes, fail = FALSE)
}
Vegetation indices from surface reflectance
Description
This function calculates one of many types of vegetation indices from a raster with four bands representing blue (B), green (G), red (R), and near infrared (NIR), plus possibly channels 5 and 7. The function requires rasters that represent surface reflectance, so should have values that fall in the range 0 to 1, unless they are digital number rasters (e.g., integers in the range 0 to 255). If digital number format is used, then the bits
argument should be defined.
Usage
## S4 method for signature 'GRaster'
vegIndex(
x,
index = "NDVI",
r = NULL,
g = NULL,
b = NULL,
nir = NULL,
b5 = NULL,
b7 = NULL,
soilSlope = NULL,
soilIntercept = NULL,
soilNR = 0.08,
bits = NULL
)
Arguments
x |
A |
index |
Character or character vector: The vegetation index or indices to calculate. You can find a list of available indices using fastData("vegIndices") (also see vegIndices). The first column, "
Note: A near-comprehensive table of indices can be found on the Index Database: A Database for Remote Sensing Indices. |
r , g , b , nir |
Numeric or character: Index or |
b5 , b7 |
Numeric or character: Index of names of the layers representing bands 5 and 7. These are used only for GVI and PVI. Values must be in the range from 0 to 1 or integers. |
soilSlope , soilIntercept , soilNR |
Numeric: Values of the soil slope, intercept, and soil noise reduction factor (0.08, by default). Used only for calculation of MSAVI. |
bits |
Either |
Value
A GRaster
.
See Also
GRASS manual page for tool i.vi
(see grassHelp("i.vi")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster, rivers vector
madLANDSAT <- fastData("madLANDSAT")
# Convert a SpatRaster to a GRaster:
landsat <- fast(madLANDSAT)
# See available vegetation indices:
vegIndices
# Normalized Difference Vegetation Index and Enhanced Vegetation Index:
indices <- c("ndvi", "evi")
vi <- vegIndex(landsat, index = indices, r = 1, b = 3, nir = 4, bits = 8)
plot(vi)
# All indices using R and NIR:
rnir <- vegIndex(landsat, index = "rnir", r = 1, nir = 4, bits = 8)
# Note: Some values are highly skewed
plot(rnir)
}
Table of vegetation indices that can be calculated from remote sensing surface reflectance data using vegIndex()
. A near-comprehensive table of indices can be found on the Index Database: A Database for Remote Sensing Indices.
Description
A table of vegetation indices that ca be calculated using vegIndex()
. Columns include:
'index“: Abbreviation of the index.
-
definition
: Index name -
R
,G
,B
,NIR
,channel5
,channel7
: Whether or not the index uses the red, green, blue, or near-infrared channels, and channels 5 and 7. -
soilLineslope
,soilIntercept
,soilNR
: Whether or not the index requires soil line slope, soil intercept, and a soil noise reduction factor.
Format
An object of class data.frame
.
See Also
Examples
### vector data
library(sf)
# For vector data, we can use data(*) or fastData(*):
data(madCoast0) # same as next line
madCoast0 <- fastData("madCoast0") # same as previous
madCoast0
plot(st_geometry(madCoast0))
madCoast4 <- fastData("madCoast4")
madCoast4
plot(st_geometry(madCoast4), add = TRUE)
madRivers <- fastData("madRivers")
madRivers
plot(st_geometry(madRivers), col = "blue", add = TRUE)
madDypsis <- fastData("madDypsis")
madDypsis
plot(st_geometry(madDypsis), col = "red", add = TRUE)
### raster data
library(terra)
# For raster data, we can get the file directly or using fastData(*):
rastFile <- system.file("extdata/madElev.tif", package="fasterRaster")
madElev <- terra::rast(rastFile)
madElev <- fastData("madElev") # same as previous two lines
madElev
plot(madElev)
madForest2000 <- fastData("madForest2000")
madForest2000
plot(madForest2000)
madForest2014 <- fastData("madForest2014")
madForest2014
plot(madForest2014)
# multi-layer rasters
madChelsa <- fastData("madChelsa")
madChelsa
plot(madChelsa)
madPpt <- fastData("madPpt")
madTmin <- fastData("madTmin")
madTmax <- fastData("madTmax")
madPpt
madTmin
madTmax
# RGB raster
madLANDSAT <- fastData("madLANDSAT")
madLANDSAT
plotRGB(madLANDSAT, 4, 1, 2, stretch = "lin")
# categorical raster
madCover <- fastData("madCover")
madCover
madCover <- droplevels(madCover)
levels(madCover) # levels in the raster
nlevels(madCover) # number of categories
catNames(madCover) # names of categories table
plot(madCover)
Voronoi tessellation
Description
This function creates a Voronoi tessellation from a set of spatial points or polygons.
Usage
## S4 method for signature 'GVector'
voronoi(x, buffer = 0)
Arguments
x |
A |
buffer |
Numeric: By default, this function creates a vector that has an extent exactly the same as the input data. However, the apparent extent can be changed by setting this value to a value different from 0. Negative values reduce the size of the extent, and positive extend it. Units are in map units. |
Value
A GVector
.
See Also
terra::voronoi()
, sf::st_voronoi()
, tool v.voronoi
in GRASS
Examples
if (grassStarted()) {
# Setup
library(sf)
# Example vectors
madDypsis <- fastData("madDypsis") # points
madCoast4 <- fastData("madCoast4") # polygons
# Convert sf vectors to GVectors
dypsis <- fast(madDypsis)
coast4 <- fast(madCoast4)
ant <- coast4[coast4$NAME_4 == "Antanambe"]
# Delaunay triangulation
dypsisDel <- delaunay(dypsis)
plot(dypsisDel)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Voronoi tessellation
vor <- voronoi(dypsis)
plot(vor)
plot(dypsis, pch = 1, col = "red", add = TRUE)
# Random Voronoi tessellation
rand <- rvoronoi(coast4, size = 100)
plot(rand)
}
Topographic wetness index
Description
This function creates a raster map with values equal to the topographic wetness index (TWI), which is a measure of how much overland water flow tends to accumulate in or flow away from a location.
Usage
## S4 method for signature 'GRaster'
wetness(x)
Arguments
x |
A |
Value
A GRaster
.
See Also
terrain()
, ruggedness()
, geomorphons()
, GRASS manual for tool r.topidx
(see grassHelp("r.topidx")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation raster
madElev <- fastData("madElev")
# Convert to GRaster:
elev <- fast(madElev)
# 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)
}
Save a GRaster to disk
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 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.
Usage
## S4 method for signature 'GRaster,character'
writeRaster(
x,
filename,
overwrite = FALSE,
datatype = NULL,
byLayer = FALSE,
names = TRUE,
levelsExt = NULL,
compress = "LZW",
warn = TRUE,
...
)
## S4 method for signature 'missing,missing'
writeRaster(x, filename)
Arguments
x |
A | |||||||||||||||||||||||||||||||||||||||||
filename |
Character: Path and file name. | |||||||||||||||||||||||||||||||||||||||||
overwrite |
Logical: If | |||||||||||||||||||||||||||||||||||||||||
datatype |
| |||||||||||||||||||||||||||||||||||||||||
byLayer |
Logical: If | |||||||||||||||||||||||||||||||||||||||||
names |
Logical: If | |||||||||||||||||||||||||||||||||||||||||
levelsExt |
Character, logical, or
| |||||||||||||||||||||||||||||||||||||||||
compress |
Character: Type of compression to use for GeoTIFF files:
| |||||||||||||||||||||||||||||||||||||||||
warn |
Logical: If | |||||||||||||||||||||||||||||||||||||||||
... |
Additional arguments. These can include:
|
Value
A GRaster
(invisibly). A raster is also saved to disk.
See Also
terra::writeRaster()
, GRASS tool r.out.gdal
(see grassHelp("r.out.gdal")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
madChelsa <- fastData("madChelsa")
### What raster formats can we attempt to write?
writeRaster()
### Save GRaster to disk (using temporary file)
elev <- fast(madElev)
filename <- tempfile(fileext = ".tif")
writeRaster(elev, filename)
# Load raster from disk
elev2 <- fast(filename)
elev2
### Save multi-layer GRaster to disk in one file (using temporary file)
chelsa <- fast(madChelsa)
filename <- tempfile(fileext = ".tif")
writeRaster(chelsa, filename)
# Load raster from disk
chelsa2 <- fast(filename)
chelsa2
### Save multi-layer GRaster to disk layer-by-layer (using temporary file)
chelsa <- fast(madChelsa)
filename <- tempfile(fileext = ".tif")
writeRaster(chelsa, filename, byLayer = TRUE)
# Load one of the rasters from disk
filename2 <- sub(filename, pattern = ".tif", replacement = "_bio1.tif")
chelsaBio1 <- fast(filename2)
chelsaBio1
}
Save a GVector to disk
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 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:
Warning 1: Invalid value type found in record 2 for field column_with_NA_or_NaN. This warning will no longer be emitted.
Also note that despite the promise, this warning will be displayed again.
Usage
## S4 method for signature 'GVector,character'
writeVector(
x,
filename,
overwrite = FALSE,
format = NULL,
attachTable = TRUE,
...
)
## S4 method for signature 'missing,missing'
writeVector(x, filename)
Arguments
x |
A |
filename |
Character: Path and file name. |
overwrite |
Logical: If |
format |
Character or
|
attachTable |
Logical: If |
... |
Additional arguments to send to GRASS tool |
Value
Invisibly returns a GRaster
(the input, x
). Also saves the vector to disk.
See Also
terra::writeVector()
, sf::st_write()
, GRASS tool v.out.ogr
(see grassHelp("v.out.ogr")
)
terra::writeVector()
, the GRASS tool manual page for v.out.ogr
(see grassHelp("v.out.ogr")
)
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data
madRivers <- fastData("madRivers")
# What file formats can we attempt to write?
writeVector()
# Convert SpatVector to GVector
rivers <- fast(madRivers)
rivers
# Save GVector to disk as GeoPackage
filename <- tempfile(fileext = ".gpkg")
writeVector(rivers, filename)
# Save GVector to disk as ESRI Shapefile
filename <- tempfile(fileext = ".shp")
writeVector(rivers, filename)
# Save GVector to disk as Google Earth KML
filename <- tempfile(fileext = ".klm")
writeVector(rivers, filename)
# Save GVector data table to disk as comma-separated file
filename <- tempfile(fileext = ".csv")
writeVector(rivers, filename)
# Save GVector data table to disk as NetCDF
filename <- tempfile(fileext = ".ncdf")
writeVector(rivers, filename)
# Save GVector data table to disk as Excel file
filename <- tempfile(fileext = ".xlsx")
writeVector(rivers, filename)
}
Select parts of polygons not shared between two GVectors
Description
The xor()
function selects the area that does not overlap between two "polygon" GVector
s. You can also use the /
operator, as in vect1 / vect2
.
Usage
## S4 method for signature 'GVector,GVector'
xor(x, y)
Arguments
x , y |
|
Value
A GVector
.
See Also
crop()
, intersect()
, union()
, erase()
Examples
if (grassStarted()) {
# Setup
library(sf)
# Polygon of coastal Madagascar and Dypsis specimens
madCoast4 <- fastData("madCoast4") # polygons
madDypsis <- fastData("madDypsis") # points
# Convert vectors:
coast4 <- fast(madCoast4)
dypsis <- fast(madDypsis)
# Create another polygons vector from a convex hull around Dypsis points
hull <- convHull(dypsis)
### union()
unioned <- union(coast4, hull)
plot(unioned)
plus <- coast4 + hull # same as union()
### intersect
inter <- intersect(coast4, hull)
plot(coast4)
plot(hull, border = "red", add = TRUE)
plot(inter, border = "blue", add = TRUE)
### xor
xr <- xor(coast4, hull)
plot(coast4)
plot(xr, border = "blue", add = TRUE)
### erase
erased <- erase(coast4, hull)
plot(coast4)
plot(erased, border = "blue", add = TRUE)
minus <- coast4 - hull # same as erase()
}
Statistics on cells of a GRaster stratified by cells of another raster
Description
Function zonal()
calculates statistics (mean, sum, etc.) on cells of a GRaster
by "zones" created by cells of another GRaster
or GVector
.
Usage
## S4 method for signature 'GRaster,ANY'
zonal(x, z, fun = "mean", probs = 0.5)
Arguments
x |
A |
z |
A
|
fun |
Character vector: Name of the function(s) to summarize
|
probs |
Numeric: Quantile at which to calculate |
Value
A data.frame
or data.table
.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Elevation SpatRaster:
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
### Calculate zonal statistics using a GRaster as zones
# Generate a "zones" GRaster by dividing raster into areas based on
# high/low elevation.
names(elev) # Use this name in app() formula.
fun <- "= if (madElev <200, 0, if (madElev <400, 1, 2))"
zones <- app(elev, fun = fun)
# Calculate zonal statistics using a raster as zones
zonal(elev, zones, fun = "mean")
zonal(elev, zones, fun = "*") # all statistics
# Calculate zonal statistics on multi-layered GRaster
elev2 <- c(elev, log10(elev))
zonal(elev2, zones, fun = c("mean", "sum", "sdpop"))
### Calculate zonal statistics using a GVector as zones
madCoast4 <- fastData("madCoast4")
coast <- fast(madCoast4)
zonal(elev, z = coast, fun = "mean")
}
Geographic statistics for sets of cells with the same values
Description
This function calculates geographic statistics for each set of cells in an integer
or factor
GRaster
. Statistics include:
Area
Perimeter length
"Compact square" statistic:
4 \sqrt(area) / perimeter)
"Compact circle" statistic:
4 * P / ( 2 \sqrt(\pi * A))
where P is the perimeter length and A the area.fractal dimension:
2 ( log(P) / log(A + 0.001))
where P is perimeter length and A is area.The average x- and y-coordinates of each zone.
Usage
## S4 method for signature 'GRaster'
zonalGeog(x, unit = "meters")
Arguments
x |
A |
unit |
Character: Units of the output. Any of:
Partial matching is used and case is ignored. |
Value
A list of data.frame
s or a data.table
s, one per layer in x
. Only layers that are integers or factors have their geographies calculated. Other layers have NULL
tables returned.
Examples
if (grassStarted()) {
# Setup
library(terra)
# Example data: Elevation and land cover
madElev <- fastData("madElev")
madForest2000 <- fastData("madForest2000")
madCover <- fastData("madCover")
# Convert to GRasters:
elev <- fast(madElev)
forest2000 <- fast(madForest2000)
cover <- fast(madCover)
# Rename
names(elev) <- "elev"
names(forest2000) <- "forest"
# Geometric statistics for an integer raster zoned by elevation:
fun <-
"= if (elev <400 & forest == 1, 0, if (elev >=400 & forest == 1, 1, null()))"
forestByElev <- app(c(elev, forest2000), fun = fun)
plot(forestByElev, main = "forest < 400 m & >= 400 m")
zonalGeog(forestByElev)
# Geometric statistics for a categorical raster:
zonalGeog(cover)
}