Title: | Faster Raster and Spatial Vector Processing Using 'GRASS GIS' |
---|---|
Description: | Processing of large-in-memory/large-on disk rasters and spatial vectors using 'GRASS GIS' <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 GIS' 8.0 or higher. |
Authors: | Adam B. Smith [cre, aut] |
Maintainer: | Adam B. Smith <[email protected]> |
License: | GPL (>=3) |
Version: | 8.4.0.4 |
Built: | 2025-01-17 06:09:45 UTC |
Source: | https://github.com/adamlilith/fasterraster |
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.
## S4 method for signature 'GVector,ANY,ANY' x[i, j] ## S4 method for signature 'GRaster,GRaster,ANY' x[i, j]
## S4 method for signature 'GVector,ANY,ANY' x[i, j] ## S4 method for signature 'GRaster,GRaster,ANY' x[i, j]
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 |
A GVector
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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.
## S4 method for signature 'GRaster,ANY,ANY' x[[i, j]] ## S4 method for signature 'GVector,ANY,ANY' x[[i, j]]
## S4 method for signature 'GRaster,ANY,ANY' x[[i, j]] ## S4 method for signature 'GVector,ANY,ANY' x[[i, j]]
x |
A |
i |
Numeric integer, integer, logical, or character: Indicates the layer(s) of a |
j |
Ignored for |
A GRaster
or GVector
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
The [[<-
operator can be used to replace a layer in a multi-layer GRaster
.
## S4 replacement method for signature 'GRaster,ANY' x[[i]] <- value
## S4 replacement method for signature 'GRaster,ANY' x[[i]] <- value
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 |
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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
.
## S4 replacement method for signature 'GRaster,missing,ANY' x[i, j] <- value ## S4 replacement method for signature 'GRaster,GRaster,ANY' x[i, j] <- value
## S4 replacement method for signature 'GRaster,missing,ANY' x[i, j] <- value ## S4 replacement method for signature 'GRaster,GRaster,ANY' x[i, j] <- value
x |
A |
i |
Either missing or a conditional statement that resolves to a |
j |
Not used |
value |
A numeric, integer, or logical value, or |
A GRaster
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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.
## S4 method for signature 'GRaster' x$name ## S4 method for signature 'GVector' x$name
## S4 method for signature 'GRaster' x$name ## S4 method for signature 'GVector' x$name
x |
A |
name |
Character: The name of a |
A GRaster
or vector of the same type as the GVector
's column.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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.
## S4 replacement method for signature 'GRaster' x$name <- value ## S4 replacement method for signature 'GVector' x$name <- value
## S4 replacement method for signature 'GRaster' x$name <- value ## S4 replacement method for signature 'GVector' x$name <- value
x |
A |
name |
Character: Name of the |
value |
Character: The name of a |
A GRaster
or the column of a GVector
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 a GRaster
.
activeCat()<-
sets the column to be used as category labels.
## 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
## 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
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 |
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
.
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) }
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) }
This function "stacks" one GRaster
with another. It has the same functionality as c()
.
## S4 replacement method for signature 'GRaster,GRaster' add(x) <- value
## S4 replacement method for signature 'GRaster,GRaster' add(x) <- value
x , value
|
A |
A GRaster
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
addCats()
and addCats()<-
add information to a categorical‘GRaster’s "levels" table.
addCats()' uses data.table::merge()
or cbind()
to do this–it does not add new rows, but rather new columns.
addCats()<-
uses rbind()
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".
## S4 method for signature 'GRaster' addCats(x, value, merge = FALSE, layer = 1) ## S4 replacement method for signature 'GRaster' addCats(x, layer = 1) <- value
## S4 method for signature 'GRaster' addCats(x, value, merge = FALSE, layer = 1) ## S4 replacement method for signature 'GRaster' addCats(x, layer = 1) <- value
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. |
A GRaster
. The "levels" table of the raster is modified.
terra::addCats()
, concats()
, combineLevels()
, droplevels()
, vignette("GRasters", package = "fasterRaster"
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) }
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) }
This function tests to see if the "addons" directory specified using faster()
actually exists, and if a particular GRASS addons module is available. The
addonsfolder and module must exists for methods that rely on particular **GRASS**
addonsto work. See
vignette("addons", package = "fasterRaster")'.
addons(x = NULL, fail = TRUE, verbose = TRUE)
addons(x = NULL, fail = TRUE, verbose = TRUE)
x |
Either |
fail |
Logical: If |
verbose |
Logical: If |
Logical.
vignette("addons", package = "fasterRaster")
if (grassStarted()) { # Does the addons folder exist? ao <- addons(fail = "warning") if (ao) print("Addons is folder is probably correctly specified.") # Does this particular module exist? addon <- "v.centerpoint" exten <- addons(addon, fail = FALSE) if (exten) print("Extension `v.centerpoints` is installed.") }
if (grassStarted()) { # Does the addons folder exist? ao <- addons(fail = "warning") if (ao) print("Addons is folder is probably correctly specified.") # Does this particular module exist? addon <- "v.centerpoint" exten <- addons(addon, fail = FALSE) if (exten) print("Extension `v.centerpoints` is installed.") }
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
.
## 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)
## 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)
x |
A |
... |
Other arguments (ignored). |
value |
A |
A GVector
.
$<-
, colbind()
, rbind()
, as.data.frame()
, as.data.table()
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 }
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 }
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
.
## 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)
## 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)
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 |
A GRaster
or GVector
.
stats::aggregate()
, terra::aggregate()
, disagg()
, terra::disagg()
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) }
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) }
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 have names()
. The function matches on these, not the name of the variable you use in R for the GRaster
.
Use null()
instead of NA
, and use isnull()
instead of is.na()
.
If you want to calculate values using while ignoring NA
(or null
) values, see the functions that begin with n
(like nmean
).
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), and DCELL
(double-floating point values–precise to about the 15th decimal place; commensurate with the R numeric
type). In cases where you want a GRaster
to be treated like a float or double type raster, wrap the name of the GRaster
in the float()
or double()
functions. This is especially useful if the GRaster
might be assumed to be the CELL
type because it only contains integer values. You can get the data type of a raster using datatype()
with the type
argument set to GRASS
. You can change the data type of a GRaster
using as.int()
, as.float()
, and as.doub()
. Note that categorical rasters are really CELL
(integer) rasters with an associated "levels" table. You can also change a CELL
raster to a FCELL
raster by adding then subtracting a decimal value, as in x - 0.1 + 0.1
. See vignette("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)
.
## 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)
## 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)
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 module |
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 |
A GRaster
.
terra::app()
, terra::lapp()
, subst()
, classify()
, and especially the GRASS manual page for module r.mapcalc
(see grassHelp("r.mapcalc")
)
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) }
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) }
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()
.
A data.frame
.
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) }
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) }
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()
## 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)
## 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)
e1 , e2
|
|
A GRaster
.
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) }
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) }
Create a GVector
of contour lines from a GRaster
.
## S4 method for signature 'GRaster' as.contour(x, nlevels, levels)
## S4 method for signature 'GRaster' as.contour(x, nlevels, levels)
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 |
A GVector
representing contour lines.
terra::as.contour()
, GRASS manual page for module r.contour
(see grassHelp("r.contour")
)
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) }
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 a GVector
's data table to a data.frame
or data.table
.
## S4 method for signature 'GVector' as.data.frame(x) ## S4 method for signature 'GVector' as.data.table(x)
## S4 method for signature 'GVector' as.data.frame(x) ## S4 method for signature 'GVector' as.data.table(x)
x |
A |
A data.frame
or NULL
(if the GRaster
has no data table).
terra::as.data.frame()
, data.table::as.data.table()
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) }
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) }
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 type CELL
).
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<-
or categories()
.
## S4 method for signature 'GRaster' as.int(x) ## S4 method for signature 'GRaster' as.float(x) ## S4 method for signature 'GRaster' as.doub(x)
## S4 method for signature 'GRaster' as.int(x) ## S4 method for signature 'GRaster' as.float(x) ## S4 method for signature 'GRaster' as.doub(x)
x |
A |
A GRaster
.
datatype()
, terra::datatype()
, is.int()
, is.float()
, is.doub()
, levels<-
, vignette("GRasters", package = "fasterRaster")
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 }
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 }
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.
## S4 method for signature 'GRaster' as.lines(x)
## S4 method for signature 'GRaster' as.lines(x)
x |
A |
A GVector
.
as.points()
, as.polygons()
, terra::as.lines()
, thinLines()
, geometry cleaning, and GRASS module r.to.vect
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) }
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) }
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.
## S4 method for signature 'GRaster' as.points(x, values = TRUE) ## S4 method for signature 'GVector' as.points(x)
## S4 method for signature 'GRaster' as.points(x, values = TRUE) ## S4 method for signature 'GVector' as.points(x)
x |
A |
values |
Logical: If |
A points
GVector
.
crds()
, as.lines()
, as.polygons()
, terra::as.points()
, and modules v.to.points
and r.to.vect
in GRASS
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) }
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) }
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.
## S4 method for signature 'GRaster' as.polygons(x, round = TRUE, smooth = FALSE)
## S4 method for signature 'GRaster' as.polygons(x, round = TRUE, smooth = FALSE)
x |
A |
round |
Logical: If |
smooth |
Logical: If |
A GVector
.
as.points()
, as.lines()
, terra::as.polygons()
, geometry cleaning, and GRASS module r.to.vect
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) }
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) }
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.
## 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 )
## 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 )
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 |
A GRaster
with one or more layers.
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.
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) }
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) }
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 to fixLines()
, 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 than tolerance
distance. If tolerance
is <0, all dangles will be changed to lines. Units of tolerance
are in map units, or in degrees for unprojected CRSs. If tolerance
<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 the break()
and removeDups()
methods.
removeBridges()
: Remove "bridges" to "islands" (which are topologically incorrect) within geometries.
removeDangles()
: Remove "dangling" lines if shorter than tolerance
distance. If tolerance
is <0, all dangles will be removed. Units of tolerance
are in map units, or in degrees for unprojected CRSs. If tolerance
<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 than tolerance
. Units of tolerance
are in square meters (regardless of the CRS).
snap()
: Snap lines/boundaries to each other if they are less than tolerance
apart. Subsequent removal of dangles may be needed. Units of tolerance
are map units, or degrees for unprojected CRSs.
## 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)
## 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)
x |
A |
tolerance |
Numeric or |
A GVector
.
terra::topology()
, fillHoles()
, terra::removeDupNodes()
, Details section in fast()
, simplifyGeom()
, smoothGeom()
, GRASS manual page for module v.clean
(see grassHelp("v.clean")
)
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") ) }
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") ) }
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.
## 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)
## 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)
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 * `"cells"`: Units are numbers of cells.
|
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 |
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 :(.
A GRaster
or a GVector
.
terra::buffer()
, sf::st_buffer()
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) }
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) }
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 all GVector
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()
.
## S4 method for signature 'GRaster' c(x, ...)
## S4 method for signature 'GRaster' c(x, ...)
x |
A |
... |
One or more |
A GRaster
.
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) }
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) }
This function returns the column names of each "levels" table of a categorical raster (see vignette("GRasters", package = "fasterRaster")
).
## S4 method for signature 'GRaster' catNames(x, layer = NULL) ## S4 method for signature 'SpatRaster' catNames(x, layer = NULL)
## S4 method for signature 'GRaster' catNames(x, layer = NULL) ## S4 method for signature 'SpatRaster' catNames(x, layer = NULL)
x |
A |
layer |
|
A list of character vectors.
cats()
, vignette("GRasters", package = "fasterRaster")
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) }
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) }
cellArea()
returns a raster will cell values equal to their area. To get the area of all cells of a raster, see expanse()
.
## S4 method for signature 'GRaster' cellSize(x, mask = FALSE, lyrs = FALSE, unit = "meters2")
## S4 method for signature 'GRaster' cellSize(x, mask = FALSE, lyrs = FALSE, unit = "meters2")
x |
A |
mask |
Logical: If |
lyrs |
Logical:
|
unit |
Character: Units of area. Partial matching is used, and case is ignored. Can be any of:
|
A GRaster
.
terra::cellSize()
, expanse()
, zonalGeog()
, omnibus::convertUnits()
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) }
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) }
This function locates the centroid of each geometry of a GVector
.
To use this function, you must a) have correctly specified the addonsDir
option using faster()
, and b) installed the GRASS addon v.centerpoint
. See addons()
and vignette("addons", package = "fasterRaster")
.
## S4 method for signature 'GVector' centroids(x, method = NULL, fail = TRUE)
## S4 method for signature 'GVector' centroids(x, method = NULL, fail = TRUE)
x |
A |
method |
Character or
Partial matching is used and case is ignored. |
fail |
Logical: If |
A points GVector
.
terra::centroids()
; GRASS addon module v.centerpoint
.
if (grassStarted()) { # Setup library(sf) library(terra) # Points, lines, and polygons madDypsis <- fastData("madDypsis") madRivers <- fastData("madRivers") madCoast4 <- fastData("madCoast4") # Convert to GVectors: dypsis <- fast(madDypsis) rivers <- fast(madRivers) coast4 <- fast(madCoast4) # Point centroids: dypMean <- centroids(dypsis, fail = FALSE) dypMedian <- centroids(dypsis, method = "median", fail = FALSE) dypPMedian <- centroids(dypsis, method = "pmedian", fail = FALSE) if (!is.null(dypMean)) { plot(dypsis) plot(dypMean, col = "red", add = TRUE) plot(dypMedian, col = "green", pch = 2, add = TRUE) plot(dypPMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mean", "median", "pmedian"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } # Line centroids: riversMid <- centroids(rivers, fail = FALSE) riversMean <- centroids(rivers, method = "mean", fail = FALSE) riversMedian <- centroids(rivers, method = "median", fail = FALSE) if (!is.null(riversMid)) { plot(rivers) plot(riversMid, col = "red", add = TRUE) plot(riversMean, col = "green", pch = 2, add = TRUE) plot(riversMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mid", "mean", "median"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } # Polygon centroids: coastMean <- centroids(coast4, fail = FALSE) coastMedian <- centroids(coast4, method = "median", fail = FALSE) coastBMedian <- centroids(coast4, method = "bmedian", fail = FALSE) if (!is.null(coastMean)) { plot(coast4) plot(coastMean, col = "red", add = TRUE) plot(coastMedian, col = "green", pch = 2, add = TRUE) plot(coastBMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mean", "median", "bmedian"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } }
if (grassStarted()) { # Setup library(sf) library(terra) # Points, lines, and polygons madDypsis <- fastData("madDypsis") madRivers <- fastData("madRivers") madCoast4 <- fastData("madCoast4") # Convert to GVectors: dypsis <- fast(madDypsis) rivers <- fast(madRivers) coast4 <- fast(madCoast4) # Point centroids: dypMean <- centroids(dypsis, fail = FALSE) dypMedian <- centroids(dypsis, method = "median", fail = FALSE) dypPMedian <- centroids(dypsis, method = "pmedian", fail = FALSE) if (!is.null(dypMean)) { plot(dypsis) plot(dypMean, col = "red", add = TRUE) plot(dypMedian, col = "green", pch = 2, add = TRUE) plot(dypPMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mean", "median", "pmedian"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } # Line centroids: riversMid <- centroids(rivers, fail = FALSE) riversMean <- centroids(rivers, method = "mean", fail = FALSE) riversMedian <- centroids(rivers, method = "median", fail = FALSE) if (!is.null(riversMid)) { plot(rivers) plot(riversMid, col = "red", add = TRUE) plot(riversMean, col = "green", pch = 2, add = TRUE) plot(riversMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mid", "mean", "median"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } # Polygon centroids: coastMean <- centroids(coast4, fail = FALSE) coastMedian <- centroids(coast4, method = "median", fail = FALSE) coastBMedian <- centroids(coast4, method = "bmedian", fail = FALSE) if (!is.null(coastMean)) { plot(coast4) plot(coastMean, col = "red", add = TRUE) plot(coastMedian, col = "green", pch = 2, add = TRUE) plot(coastBMedian, col = "orange", pch = 1, add = TRUE) legend("bottomright", legend = c("mean", "median", "bmedian"), col = c("red", "green", "orange"), pch = c(16, 2, 1), xpd = NA ) } }
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.
## S4 method for signature 'GRaster' classify(x, rcl, include.lowest = FALSE, right = TRUE, others = NULL)
## S4 method for signature 'GRaster' classify(x, rcl, include.lowest = FALSE, right = TRUE, others = NULL)
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 |
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")
.
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) }
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) }
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.
## S4 method for signature 'GRaster' clump(x, minDiff = 0, minClumpSize = 1, diagonal = TRUE)
## S4 method for signature 'GRaster' clump(x, minDiff = 0, minClumpSize = 1, diagonal = TRUE)
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 |
A GRaster
.
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 }
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 }
clusterPoints()
partitions points in a "points" GVector
into clusters.
## S4 method for signature 'GVector' clusterPoints(x, method = "DBSCAN", minIn = NULL, maxDist = NULL)
## S4 method for signature 'GVector' clusterPoints(x, method = "DBSCAN", minIn = NULL, maxDist = NULL)
x |
A "points" |
method |
Character: Method used to identify clusters. Explanations of methods are provided in the help page for the GRASS module
Case is ignored, but partial matching is not used. |
minIn |
Integer, numeric integer, or |
maxDist |
Numeric or |
A vector of integers indicating the cluster to which each point belongs.
GRASS manual page for module v.cluster
(see grassHelp("v.cluster")
)
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()
.
## S4 method for signature 'GVector' colbind(x, ...)
## S4 method for signature 'GVector' colbind(x, ...)
x , ...
|
The first argument must be a |
A GVector
.
rbind()
, addTable<-
, dropTable()
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 }
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 }
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.
## S4 method for signature 'GRaster' combineLevels(x, ...) ## S4 method for signature 'list' combineLevels(x, ...)
## S4 method for signature 'GRaster' combineLevels(x, ...) ## S4 method for signature 'list' combineLevels(x, ...)
x |
A |
... |
Arguments to pass to |
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.
concats()
, terra::concats, vignette("GRasters", package = "fasterRaster")
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) }
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) }
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.
## 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)
## 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)
e1 , e2
|
Values depend on the type of comparison:
|
Comparing GRaster
s: An "integer" GRaster
with values of 0 (FALSE), 1 (TRUE), or NA
(neither).
Comparing GRegion
s: Output is logical.
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 }
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 }
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.).
## 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 )
## 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 )
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 |
Logical (invisibly): TRUE
for no mismatches detected, FALSE
for incompatibility), or side effect of throwing an error.
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.
## 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(...)
## 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(...)
... |
A |
levels |
Logical ( |
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 or NA
s, as per above.
A GVector
with a data table: A logical vector.
A GVector
without a data table: NA
.
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) }
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) }
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.
## S4 method for signature 'GRaster' compositeRGB(r, g = NULL, b = NULL, levels = 256, dither = FALSE)
## S4 method for signature 'GRaster' compositeRGB(r, g = NULL, b = NULL, levels = 256, dither = FALSE)
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 |
A GRaster
.
plotRGB()
, terra::plotRGB()
, GRASS manual page for module r.composite
(see grassHelp("r.composite")
)
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) }
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) }
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.
## S4 method for signature 'GRaster' concats(x, ..., na.rm = TRUE)
## S4 method for signature 'GRaster' concats(x, ..., na.rm = TRUE)
x |
A |
... |
Either missing or integer/categorical (factor) |
na.rm |
Logical: If |
A GRaster
. If the inputs are all categorical (factor) rasters, then a levels table will also be returned with the new combined levels.
combineLevels()
, terra::concats()
, vignette("GRasters", package = "fasterRaster")
, GRASS manual page for module r.cross
(see grassHelp("r.cross")
)
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) }
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) }
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
.
## S4 method for signature 'GVector,GVector' connectors(x, y, minDist = NULL, maxDist = NULL)
## S4 method for signature 'GVector,GVector' connectors(x, y, minDist = NULL, maxDist = NULL)
x , y
|
|
minDist , maxDist
|
Either |
A GVector
with a data table that has the length of each connecting line in meters.
GRASS manual for module v.distance
(see grassHelp("v.distance")
).
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) }
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) }
Create a minimum convex hull around a spatial vector.
## S4 method for signature 'GVector' convHull(x, by = "")
## S4 method for signature 'GVector' convHull(x, by = "")
x |
A |
by |
Character: If |
A GVector
.
terra::convHull()
, sf::st_convex_hull()
, module v.hull
in GRASS
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) } }
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) } }
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()
.
## 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)
## 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)
x |
A |
z |
If |
na.rm |
Logical: If |
A matrix
, data.frame
, or list
.
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) }
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) }
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()
.
## S4 method for signature 'GRaster' crop(x, y, fail = TRUE) ## S4 method for signature 'GVector' crop(x, y, extent = FALSE, fail = TRUE)
## S4 method for signature 'GRaster' crop(x, y, fail = TRUE) ## S4 method for signature 'GVector' crop(x, y, extent = FALSE, fail = TRUE)
x |
A |
y |
A |
fail |
Logical: If |
extent |
Logical:
|
Known differences from terra::crop()
:
If x
and y
are "points" vectors, and extent
is TRUE
, terra removes points that fall on the extent boundary. fasterRaster does not remove points on the extent boundary.
If x
is a "points" vector and y
is a "lines" vectors, and extent
is FALSE
, terra uses the extent of y
to crop the points. fasterRaster uses the minimum convex hull of the lines vector.
A GRaster
or GVector
(or NULL
if fail
is FALSE
and the output would have a zero east-west and/or north-south extent).
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" ) }
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" ) }
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 class character
).
st_crs()
: Return a crs
object (from the sf package).
coordRef()
: Return a list
.
## 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)
## 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)
x |
An object that inherits from a |
... |
Other arguments (generally unused). |
Function crs()
returns a character
object, st_crs()
returns crs
object, and coordRef()
a list
.
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 }
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 }
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.
## S4 method for signature 'GRaster' datatype(x, type = "fasterRaster", forceDouble = TRUE) ## S4 method for signature 'GVector' datatype(x)
## S4 method for signature 'GRaster' datatype(x, type = "fasterRaster", forceDouble = TRUE) ## S4 method for signature 'GVector' datatype(x)
x |
A |
type |
(
|
forceDouble |
Logical ( |
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
.
terra::datatype()
, vignette("GRasters", package = "fasterRaster")
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) }
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) }
This function creates a Delaunay triangulation from a "points" GVector
.
## S4 method for signature 'GVector' delaunay(x)
## S4 method for signature 'GVector' delaunay(x)
x |
A |
A GVector
.
terra::delaunay()
, module v.delaunay
in GRASS
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) }
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) }
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".
## S4 method for signature 'GRaster' denoise(x, scale = FALSE, percent = 80) ## S4 method for signature 'GRaster' noise(x, scale = FALSE, percent = 80)
## S4 method for signature 'GRaster' denoise(x, scale = FALSE, percent = 80) ## S4 method for signature 'GRaster' noise(x, scale = FALSE, percent = 80)
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 |
A multi-layer GRaster
with one layer per input.
princomp()
, stats::prcomp()
, GRASS manual page for module i.pca
(see grassHelp("i.pca")
)
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) }
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) }
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
## 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)
## 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)
x |
A |
A numeric value or vector.
ngeom()
, nsubgeom()
, nacell()
, nonnacell()
, terra::dim()
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) }
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) }
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()
.
## S4 method for signature 'GVector' disagg(x)
## S4 method for signature 'GVector' disagg(x)
x |
A |
A GVector
.
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) }
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) }
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.
## 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)
## 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)
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 |
If x
is a GRaster
, then the output is a GRaster
. If x
is a GVector
, then the output is a numeric vector.
terra::distance()
; GRASS modules r.grow.distance
and v.distance
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 }
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 }
droplevels()
removes levels (category values) from the "levels" table of a categorical GRaster
.
## S4 method for signature 'GRaster' droplevels(x, level = NULL, layer = 1)
## S4 method for signature 'GRaster' droplevels(x, level = NULL, layer = 1)
x |
A |
level |
|
layer |
Numeric integers, logical vector, or character: Layer(s) to which to add or from which to drop levels. |
A GRaster
. The "levels" table of the raster is modified.
missingCats()
, missing.cases()
, terra::droplevels()
, vignette("GRasters", package = "fasterRaster")
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) }
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) }
As of September of 2023, the data.table package does not have a function for removing rows by index. This function does this job.
## 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)
## 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)
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 |
A data.table
or data.frame
.
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
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
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
).
## S4 method for signature 'GVector,GVector' erase(x, y)
## S4 method for signature 'GVector,GVector' erase(x, y)
x , y
|
|
A GVector
.
c()
, aggregate()
, crop()
, intersect()
, union()
, xor()
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() }
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() }
This function calculates the area of each polygon in a "polygons" GVector
or the length of lines in a "lines" GVector
.
## S4 method for signature 'GVector' expanse(x, unit = "m")
## S4 method for signature 'GVector' expanse(x, unit = "m")
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. |
Numeric values, one per geometry in x
.
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) }
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) }
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 not NA
only if the object is 3-dimensional.
W()
, E()
, N()
, S()
: Coordinates of one side of horizontal extent.
top()
and bottom()
: Coordinates of top and bottom of vertical extent.
## 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)
## 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)
x |
An object that inherits from |
vector |
Logical: If |
char |
Logical: If |
The returned values depend on the function:
ext()
: A SpatExtent
object (terra package) or a numeric vector.
zext()
: A numeric vector.
W()
, E()
, N()
, S()
, top()
, and bottom()
: A numeric value or character.
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) }
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) }
extend()
adds cells around a raster, making it larger.
## 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)
## 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)
x |
A |
y |
Any of:
|
fill |
Numeric: Value to place in the new cells. The default is |
snap |
Character: Method used to align
|
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.
A GRaster
.
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) }
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()
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 integer GRaster
and y
is a points GVector
: Returns values of cells that have points. If xy
is TRUE
, also returns the coordinates of the points.
Case #2: x
is a categorical (factor) GRaster
and y
is a points GVector
: Same as case #1, but if cats
is TRUE
, returns category labels of cells that have points. If xy
is TRUE
, also returns the coordinates of the points.
Case #3: x
is a categorical GRaster
and y
is a lines or polygons GVector
: Returns a summary (e.g., mean, standard deviation, etc.) of all cells that overlap the line(s) or polygon(s).
Case #4: x
is a GVector
and y
is a points GVector
: Returns the data table row associated each point. If xy
is TRUE
, also returns the coordinates of the points.
Note that whenever a points GVector
is allowed for y
, a data.frame
, data.table
, matrix
, or numeric
values representing points can be used instead.
## 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)
## 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)
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 |
A data.frame
or data.table
.
terra::extract()
, and modules r.what
and v.what
in GRASS
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 }
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 }
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.
## 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)
## 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)
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 |
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 the correct = 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, like snap = 0.000001
. Units of snap
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 the area
argument followed by a numeric value (e.g., area = 1
). The units of area
are in meters-squared, regardless of the coordinate reference system. Note that using snap
and area
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/or area
correction on polygons vectors by setting snap
and/or area
to NULL
(i.e., their default values). If just snap
is NULL
, only automatic snapping will be performed, and if just area
is NULL
, then only automatic area removal will be performed. Regardless, you will also need to set an integer value for steps
, which is the number of steps to take between the smallest value of snap
and/or area
and the maximum value attempted. The function will then proceed by first attempting snap = 0
and/or area = 0
(i.e., no snapping or area removal). If this does not produce a topologically correct vector, GRASS will (internally) suggest a range for snap
. The fast()
function then creates steps
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 of snap
is reached and results in a failed topology. Smaller values of step
will result in more fine-grained attempts so are less likely to yield overcorrection, but can also take more time. The value of area
in automatic correction is set to snap^2
. NB: Automated snapping and area removal are only performed on polygons vectors, even if snap
or area
is NULL
. To snap lines or points, you must set snap
equal to a numeric value. The area
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 by snap
and area
. Aggregation/disaggregation will cause any associated data table to be dropped (it forces dropTable
to be TRUE
). The default action is to do neither aggregation nor disaggregation (resolve = NA
).
If none of these fixes work, you can try:
Correction outside of fasterRaster: Before you convert the vector into fasterRaster's GVector
format, you can also try using the terra::makeValid()
or sf::st_make_valid()
tools to fix issues, then use fast()
.
Post-conversion to a GVector
: If you do get a vector loaded into GVector
format, you can also use a set of fasterRaster vector-manipulation tools or fillHoles()
to fix issues.
A GRaster
or GVector
.
rgrass::read_RAST()
and rgrass::read_VECT()
, vector cleaning, fillHoles()
, plus GRASS modules v.in.ogr
(see grassHelp("v.in.ogr")
) and r.import
(see grassHelp("r.import")
)
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 }
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 }
This function is a simple way to get example rasters or spatial vector datasets that come with fasterRaster.
fastData(x)
fastData(x)
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
|
A SpatRaster
, sf
spatial vector, or a data.frame
.
### 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)
### 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)
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.
faster(..., default = FALSE, restore = FALSE)
faster(..., default = FALSE, restore = FALSE)
... |
Either:
Options include:
|
default |
Logical: Return the default value(s) of the option(s). The default value of |
restore |
Logical: If |
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).
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 } }
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 } }
fillHoles()
removes holes in a GVector
.
## S4 method for signature 'GVector' fillHoles(x, fail = TRUE)
## S4 method for signature 'GVector' fillHoles(x, fail = TRUE)
x |
A |
fail |
Logical: If |
A GVector
.
terra::fillHoles()
, GRASS manual page for module v.fill.holes
(see grassHelp("v.fill.holes")
)
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) }
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) }
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.
## S4 method for signature 'GRaster' fillNAs( x, lambda = NULL, method = "bilinear", min = -Inf, max = Inf, cells = Inf )
## S4 method for signature 'GRaster' fillNAs( x, lambda = NULL, method = "bilinear", min = -Inf, max = Inf, cells = Inf )
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- |
A GRaster
.
terra::interpNear()
, GRASS module r.fillnulls
(see grassHelp("r.fillnulls")
)
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) }
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) }
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 module r.terraflow
] (see grassHelp("r.terraflow")
)
## S4 method for signature 'GRaster' flow( x, direction = "multi", return = "accumulation", dirThreshold = Inf, scratchDir = NULL )
## S4 method for signature 'GRaster' flow( x, direction = "multi", return = "accumulation", dirThreshold = Inf, scratchDir = NULL )
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 |
A GRaster
.
flowPath()
, streams()
, the GRASS module r.terraflow
(see grassHelp("r.terraflow")
)
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) }
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) }
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
.
## S4 method for signature 'GRaster' flowPath(x, y, return = "ID")
## S4 method for signature 'GRaster' flowPath(x, y, return = "ID")
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.
|
A GRaster
.
flow()
, streams()
, the GRASS module r.drain
(see grassHelp("r.drain")
)
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 }
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 }
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).
## S4 method for signature 'GRaster' focal(x, w = 3, fun = "sum", circle = FALSE, quantile = 0.5)
## S4 method for signature 'GRaster' focal(x, w = 3, fun = "sum", circle = FALSE, quantile = 0.5)
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 |
A GRaster
.
terra::focal()
, GRASS manual page for module r.neighbors
(see grassHelp("r.neighbors")
)
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) }
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) }
fractalRast()
creates a raster with a fractal pattern.
## S4 method for signature 'GRaster' fractalRast(x, n = 1, mu = 0, sigma = 1, dimension = 2.05)
## S4 method for signature 'GRaster' fractalRast(x, n = 1, mu = 0, sigma = 1, dimension = 2.05)
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. |
A GRaster
.
rSpatialDepRast()
, rnormRast()
, runifRast()
, GRASS manual page for module r.surf.fractal
(see grassHelp("r.surf.fractal")
)
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) }
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) }
Riitters et al. (2020) propose a classification scheme for forest fragmentation (which can be applied to any habitat type). The scheme relies on calculating density (e.g., number of forested cells in a window around a focal cell) and connectivity (number of cases where neighboring cells are both forested). This function calculates these classes from a GRaster
or SpatRaster
in which the focal habitat type has cell values of 1, and non-focal habitat type has cell values of 0 or NA
.
Note that by default, the SpatRaster
and GRaster
versions will create different results around the border of the raster. The SpatRaster
version uses the terra::focal()
function, which will not return an NA
value when its window overlaps the raster border if the na.rm
argument is TRUE
. However, the GRaster
version uses the GRASS module r.neighbors
, which does return NA
values in these cases.
The fragmentation classes are:
Value provided by none
: None (i.e., no forest; default is NA
).
1: Patch
2: Transitional
3: Perforated
4: Edge
5: Undetermined (not possible to obtain when w = 3
)
6: Interior
## 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)
## 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)
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 |
A categorical SpatRaster
or GRaster
. The values assigned to each class can be seen with levels()
.
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.
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) }
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) }
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.
## S4 method for signature 'GRaster' freq(x, digits = 3, bins = 100, value = NULL)
## S4 method for signature 'GRaster' freq(x, digits = 3, bins = 100, value = NULL)
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 |
A data.frame
or a named list
of data.frame
s, one per layer in x
.
terra::freq()
, module r.stats
in GRASS
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) }
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) }
Geomorphons are idealized terrain types calculated from an elevator raster based on a moving window of a given size. The window is a torus (which can have an inner radius of 0, so can also be a circle), which allows it to identify geomorphons of a given size while ignoring ones larger or smaller. There are 10 basic geomorphons. Consult the the manual for GRASS module r.geomorphon
using grassHelp("r.geomorphon")
for more details and diagrams of each type of geomorphon. Geomorphon types include:
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
## S4 method for signature 'GRaster' geomorphons( x, inner = 0, outer = 3, unit = "cells", flat = 1, flatDist = 0, mode = "1" )
## S4 method for signature 'GRaster' geomorphons( x, inner = 0, outer = 3, unit = "cells", flat = 1, flatDist = 0, mode = "1" )
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:
|
A categorical GRaster
where each geomorphon is a category (see vignette("GRasters", package = "fasterRaster")
).
GRASS manual for module r.geomorphon
(see grassHelp("r.geomorphon")
)
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) }
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) }
geomtype()
reports whether a GVector
represents points, lines, or polygons. The "is.*
" functions test whether the GVector
represents points, lines, or polygons.
## 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)
## 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)
x |
A |
grass |
Logical: If |
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
.
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) }
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) }
global()
calculates a summary statistic across all the cells of a GRaster
. It returns a single value for each layer of the raster.
## S4 method for signature 'GRaster' global(x, fun = "mean", probs = seq(0, 1, 0.25), ...) ## S4 method for signature 'missing' global(x, ...)
## S4 method for signature 'GRaster' global(x, fun = "mean", probs = seq(0, 1, 0.25), ...) ## S4 method for signature 'missing' global(x, ...)
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). |
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.
terra::global()
and GRASS module r.univar
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 }
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 }
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"(see vignette("projects_mapsets", package = "fasterRaster")
), and coordinate reference system. Contained by all the rest.
The GSpatial
class contains the GLocation
class and stores information about spatial objects (extent, topology) plus the name of the file representing it in GRASS (its source
). Contained by GRegion
, GRaster
, and GVector
.
The GRegion
class contains the GSpatial
class and stores information about grids (dimensions and resolution). They do have sources
, but these are not used (they're always NA
). Contained by GRaster
. The GRegion
corresponds to GRASS "regions", though GRegion
objects are not actually pointers to GRASS "region" files (see vignette("regions", package = "fasterRaster")
).
The GRaster
class contains the GRegion
class and represents rasters. It stores information on number of layers, categories, min/max values, and user-friendly names. Categorical GRaster
s are associated with a "levels" table for representing categorical data (e.g., wetlands, forest, etc.).
The GVector
class contains the GSpatial
class and represents spatial vectors. It may or may not have an associated data.table
(i.e., a data.frame
), which contains metadata about each geometry in the vector.
An object of class GLocation
, GSpatial
, GRegion
, GRaster
, or GVector
.
location
Character (all classes): The GRASS "project"/"location" of the object. The default value is default
. Can be obtained using the hidden function .location()
. See vignette("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()
. See vignette("projects_mapsets", package = "fasterRaster")
.
workDir
Character (all classes): Directory in which GRASS stores files.
topology
Character (GSpatial
objects, including GRegion
s, GRaster
s, and GVector
s): Valid values are 2D
(2-dimensional–most rasters and vectors) or 3D
(3-dimensional–e.g., LIDAR data). Can be obtained using topology()
.
sources
Character (GRaster
s and GVector
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 using sources()
.
names
Character (GRaster
s only): Name of a raster or each raster layer in. Can be obtained using names()
.
crs
Character (all classes): Coordinate reference systems string (preferably in WKT2 format). Can be obtained using crs()
or st_crs()
.
projection
Character: The GRASS "projection" for a GRaster
or GVector
. Can be obtained using .projection()
.
dimensions
Dimensions:
GRegion
s and GRaster
s: Vector of three integers indicating number of rows, columns, and depths (for 3D objects). Can be obtained using dim()
, plus nrow()
, ncol()
, and ndepth()
.
GVectors
s: Vector of two integers indicating number of geometries and number of fields. Can be obtained using dim()
, plus nrow()
and ncol()
.
extent
Numeric vector with four values (GSpatial
objects, including GRegion
s, GRaster
s, and GVector
s): Extent of the object listed in order from westernmost longitude, easternmost longitude, southernmost latitude, northernmost latitude. Can be obtained using ext()
.
zextent
Numeric (GSpatial
objects, including GRegion
s, GRaster
s, and GVector
s): Bottom- and top-most extents of 3D GRaster
s and GVector
s. Can be obtained using zext()
.
geometry
Character (GVectors
s): Either points
, lines
, or polygons
. Can be obtained using geomtype()
.
nLayers
Integer (GRaster
s): Number of layers ("stacked" rasters–different from number of depths of 3D rasters). Can be obtained using nlyr()
.
nGeometries
Integer (GVector
s): Number of features (points, lines, or polygons). Can be obtained using nrow()
.
datatypeGRASS
Character (GRaster
s): Type of data stored in a raster, as interpreted by GRASS
. This is either CELL
(integers), FCELL
(floating-point values), or DCELL
(double-values). Can be obtained using datatype()
.
resolution
Vector of two numeric values (GRegion
s, including GRaster
s): Size of a raster cell in the east-west direction and in the north-south direction. Can be obtained using res()
and res3d()
.
minVal,maxVal
Numeric (GRaster
s): Minimum and maximum value across all cells. Can be obtained using minmax()
.
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
is 2
, then the user would see "1" when printed. Can be obtained using activeCat()
.
levels
List of data.table
s (GRaster
s): Tables for categorical rasters. If a raster is not categorical, the data.table
is NULL
, as in data.table(NULL)
. Can be obtained using levels()
or cats()
.
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 be data.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).
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()
.
## S4 method for signature 'missing' grassGUI()
## S4 method for signature 'missing' grassGUI()
Nothing (starts the GRASS GUI).
if (grassStarted()) { # DANGER: Making changes to rasters/vectors in the GUI can "break" them in R. if (interactive()) grassGUI() }
if (grassStarted()) { # DANGER: Making changes to rasters/vectors in the GUI can "break" them in R. if (interactive()) grassGUI() }
This function opens the manual page for a GRASS module (function) in your browser.
grassHelp(x, online = FALSE)
grassHelp(x, online = FALSE)
x |
Character: Any of:
|
online |
Logical: If |
Nothing (opens a web page).
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") }
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") }
Report the GRASS citation, version/release year, version number, or copyright information.
grassInfo(x = "citation")
grassInfo(x = "citation")
x |
Character: What to return. Any of:
Partial matching is used and case is ignored. |
Character.
if (grassStarted()) { # Citation grassInfo() # Version number grassInfo("version") # Version number grassInfo("versionNumber") # Version number grassInfo("versionNumber") # Copyright grassInfo("copyright") }
if (grassStarted()) { # Citation grassInfo() # Version number grassInfo("version") # Version number grassInfo("versionNumber") # Version number grassInfo("versionNumber") # Copyright grassInfo("copyright") }
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.
grassStarted()
grassStarted()
Logical.
grassStarted()
grassStarted()
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.
## 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)
## 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)
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). |
A GVector
.
hexagons()
, module v.mkgrid
in GRASS
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) }
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 the first or last part of a GVector
's data table.
## S4 method for signature 'GVector' head(x, n = 6L, keepnums = TRUE, ...) ## S4 method for signature 'GVector' tail(x, n = 6L, keepnums = TRUE, ...)
## S4 method for signature 'GVector' head(x, n = 6L, keepnums = TRUE, ...) ## S4 method for signature 'GVector' tail(x, n = 6L, keepnums = TRUE, ...)
x |
A |
n |
Integer: Number of rows to display. |
keepnums |
Logical: If no |
... |
Other arguments. |
A data.table
or data.frame
.
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) }
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) }
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.
## 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)
## 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)
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). |
A GVector
.
grid()
, module v.mkgrid
in GRASS
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) }
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) }
Hillshade rasters are often used for display purposes because they make topographical relief look "real" to the eye.
## S4 method for signature 'GRaster' hillshade(x, angle = 45, direction = 0, zscale = 1)
## S4 method for signature 'GRaster' hillshade(x, angle = 45, direction = 0, zscale = 1)
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 module |
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. |
A GRaster
.
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) }
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) }
This function creates a histogram of values in GRaster
. The function is modeled after graphics::hist()
, but actually uses graphics::barplot()
.
## S4 method for signature 'GRaster' hist(x, layer, maxnl = 16, bins = 30, freq = TRUE, ...)
## S4 method for signature 'GRaster' hist(x, layer, maxnl = 16, bins = 30, freq = TRUE, ...)
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 |
A named list of data.frame
s (invisibly), one per layer plotted, and creates a graph.
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) }
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) }
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.
## S4 method for signature 'GRaster' horizonHeight( x, units = "radians", step = 90, northIs0 = TRUE, bufferZone = 0, distance = 1, maxDist = NULL )
## S4 method for signature 'GRaster' horizonHeight( x, units = "radians", step = 90, northIs0 = TRUE, bufferZone = 0, distance = 1, maxDist = NULL )
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 |
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.
GRASS manual page for module r.horizon
(see grassHelp("r.horizon")
)
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) }
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) }
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.
## S4 method for signature 'GRaster' init(x, fun, odd = TRUE, vals = c(0, 1))
## S4 method for signature 'GRaster' init(x, fun, odd = TRUE, vals = c(0, 1))
x |
A |
fun |
Character: Any of:
|
odd |
Logical: If |
vals |
Vector of two numeric values: If |
A GRaster
with as many layers as x
.
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) }
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) }
This function interpolates values from a set of points to a raster using inverse distance weighting (IDW).
## S4 method for signature 'GVector,GRaster' interpIDW(x, y, field, nPoints = Inf, power = 2)
## S4 method for signature 'GVector,GRaster' interpIDW(x, y, field, nPoints = Inf, power = 2)
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 |
A GRaster
.
terra::interpIDW()
, interpSplines()
, fillNAs()
, GRASS module v.surf.idw
(se grassHelp("v.surf.idw")
)
This function interpolates values in the data table of a "points" GVector
to a GRaster
using splines with Tykhonov regularization to avoid overfitting.
## 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) )
## 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) )
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 |
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
).
Output depends on values of lambda
and interpolate
:
lambda
is NULL
and interpolate
is TRUE
: A GRaster
with an attribute named lambdas
. This is a data.frame
with values of lambda
that were assessed, plus mean
(mean residual value) and rms
(root mean square error). You can see the table using attr(output_raster, "lambdas", exact = TRUE)
.
lambda
is NULL
and interpolate
is FALSE
: A data.frame
with values of lambdas
that were assessed, plus mean
(mean residual value) and rms
(root mean square error). You can see the table using attr(output_raster, "lambdas", exact = TRUE)
.
lambda
is a number (interpolate
is ignored): A GRaster
.
interpIDW()
, fillNAs()
, GRASS module v.surf.bspline
(see grassHelp("v.surf.bspline")
)
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
).
## S4 method for signature 'GVector,GVector' intersect(x, y)
## S4 method for signature 'GVector,GVector' intersect(x, y)
x , y
|
|
A GVector
.
c()
, aggregate()
, crop()
, union()
, xor()
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() }
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 whether a GRaster
or GVector
is 2- or 3-dimensional.
## S4 method for signature 'GSpatial' is.2d(x) ## S4 method for signature 'GSpatial' is.3d(x)
## S4 method for signature 'GSpatial' is.2d(x) ## S4 method for signature 'GSpatial' is.3d(x)
x |
An object that inherits from the |
Logical.
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) }
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) }
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 that is.int()
will return FALSE
for categorical rasters, even though cell values are technically integers.
is.cell()
: Are values integers (TRUE
for integer
and categorical rasters).
is.float()
: Are values floating-point precision?
is.doub()
: Are values double-floating point precision?
## 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)
## 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)
x |
A |
Logical.
datatype()
, terra::datatype()
, as.int()
, as.float()
, as.doub()
, is.factor()
, vignette("GRasters", package = "fasterRaster")
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 }
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 }
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.
## S4 method for signature 'character' is.lonlat(x) ## S4 method for signature 'GLocation' is.lonlat(x) ## S4 method for signature 'sf' is.lonlat(x)
## S4 method for signature 'character' is.lonlat(x) ## S4 method for signature 'GLocation' is.lonlat(x) ## S4 method for signature 'sf' is.lonlat(x)
x |
A WKT coordinate reference string or an object from which on can be obtained (e.g., a |
Logical (TRUE
if unprojected, FALSE
otherwise).
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 as log(x + 1)
)
log10p()
(same as log(x + 1, base = 10)
)
Power functions:
sqrt()
x^y
Rounding:
round()
floor()
(round down)
ceiling()
(round up)
trunc()
(remove decimal portion)
## 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)
## 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)
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 |
A GRaster
.
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) }
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()
creates a raster using a kernel density estimator of the density of points in a "points" GVector
.
## S4 method for signature 'GVector' kernel(x, y, kernel = "Epanechnikov", optimize = TRUE, h = NULL)
## S4 method for signature 'GVector' kernel(x, y, kernel = "Epanechnikov", optimize = TRUE, h = NULL)
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 |
A GRaster
.
GRASS manual page for module v.kernel
(see grassHelp("v.kernel")
)
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) }
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) }
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).
## S4 method for signature 'GRaster' layerCor(x, fun = "cor")
## S4 method for signature 'GRaster' layerCor(x, fun = "cor")
x |
A |
fun |
Character: Name of the statistic to calculate; either |
A numeric matrix
.
terra::layerCor()
, stats::cor()
, stats::cov()
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") }
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") }
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")).
## 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
## 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
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 |
Values returned are:
levels()
and cats()
: A list of data.frame
s or data.table
s, one per raster layer.
levels()<-
and categories()
: A GRaster
.
terra::levels()
, levels<-
, terra::cats()
, terra::categories()
, see vignette("GRasters", package = "fasterRaster")
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) }
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) }
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 another GRaster
A GRaster
to a logical value (TRUE
or FALSE
, but not NA
–see not.na()
)
A GRaster
to a numeric or integer value that is 0 or 1
Operators include:
|
: TRUE
if either condition is TRUE
(or 1), but returns NA
if either condition is NA
.
&
: TRUE
if both conditions are TRUE
(or 1), but NA
if either is NA
.
## 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)
## 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)
e1 , e2
|
Two |
A binary GRaster
(1 ==> TRUE
, 0 ==> FALSE
, plus NA
when comparison results in NA
).
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 }
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 }
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.
## S4 method for signature 'GRaster' longlat(x, degrees = TRUE)
## S4 method for signature 'GRaster' longlat(x, degrees = TRUE)
x |
A |
degrees |
Logical: If |
A GRaster
stack.
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! }
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 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)
An object of class SpatRaster
in unprojected (WGS84) coordinates.
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
### 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)
### 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)
Borders of a selected portion of Madagascar
ESRI Shapefile.
Database of Global Administrative Areas Version 2.8 (GADM)
### 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)
### 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)
Borders of a selected portion of Madagascar
data(madCoast4)
data(madCoast4)
An object of class sf
.
Database of Global Administrative Areas Version 2.8 (GADM)
### 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)
### 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)
Borders of a selected portion of Madagascar
data(madCoast4)
data(madCoast4)
An object of class sf
.
Database of Global Administrative Areas Version 2.8 (GADM)
### 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)
### 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. Note that the land cover classes have been simplified, so this raster should not be used for "real" analyses.
An object of class SpatRaster
in unprojected (WGS84) coordinates.
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.
madCoverCats, vignette("GRasters", package = "fasterRaster")
### 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)
### 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)
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.
An object of class data.frame
.
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.
madCover, vignette("GRasters", package = "fasterRaster")
### 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)
### 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 herbarium specimens and observations of plants in the genus Dypsis (slender, evergreen palms) from a portion of eastern Madagascar.
data(madDypsis)
data(madDypsis)
An object of class sf
.
Global Biodiversity Information Facility (GBIF)
### 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)
### 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.
An object of class SpatRaster
. Values are mean meters above sea level.
### 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)
### 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 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
).
An object of class SpatRaster
.
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.
### 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)
### 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 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
).
An object of class SpatRaster
..
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.
### 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)
### 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 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.
An object of class SpatRaster
in Universal Trans-Mercator (UTM), Zone 39 North with a WGS84 coordinate system, at 90 m resolution.
United States Geological Survey's EarthExplorer. Also see band definitions.
### 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)
### 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 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.
An object of class SpatRaster
.
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
### 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)
### 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 lines object of major rivers in a portion of Madagascar.
data(madRivers)
data(madRivers)
An object of class sf
.
### 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)
### 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 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.
An object of class SpatRaster
.
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
### 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)
### 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 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.
An object of class SpatRaster
.
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
### 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)
### 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)
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.
## 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)
## 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)
x |
A |
mask |
A |
inverse |
Logical: If |
maskvalues |
Numeric vector, including |
updatevalue |
Numeric, including |
A GRaster
.
terra::mask()
, GRASS module r.mask
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)) }
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)) }
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.
## S4 method for signature 'GRaster' maskNA(x, value = 1, invert = FALSE, retain = FALSE)
## S4 method for signature 'GRaster' maskNA(x, value = 1, invert = FALSE, retain = FALSE)
x |
A |
value |
Numeric: Value to which to assign to masked cells. The default is 1. |
invert |
Logical: If |
retain |
Logical: If |
A GRaster
.
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)) }
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)) }
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.
## 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
## 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
x |
A |
table |
A numeric, integer, or character vector. |
nomatch |
Numeric or integer: Value to return when no match is found. |
A GRaster
.
terra::match()
, match()
, omnibus::notIn()
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) }
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) }
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 argument probs
), skewness()
, and kurtosis()
.
NA
s: anyNA()
(any cells are NA
?), allNA()
(are all cells NA
?)
## 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)
## 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)
x |
A |
na.rm |
Logical: If |
pop |
Logical (for |
prob |
Numeric: Quantile to calculate. Used for |
A GRaster
.
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) }
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) }
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.
## S4 method for signature 'GRaster,GRaster' merge(x, y, ...)
## S4 method for signature 'GRaster,GRaster' merge(x, y, ...)
x , y , ...
|
|
A GRaster
.
terra::merge()
, terra::mosaic()
, and GRASS module r.patch
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!") }
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!") }
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
.
## S4 method for signature 'GRaster' minmax(x, levels = FALSE)
## S4 method for signature 'GRaster' minmax(x, levels = FALSE)
x |
A |
levels |
Logical: If |
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.
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 }
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 }
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.
## S4 method for signature 'GRaster' missingCats(x, layer = 1:nlyr(x))
## S4 method for signature 'GRaster' missingCats(x, layer = 1:nlyr(x))
x |
A |
layer |
Numeric integers, logical vector, or character: Layer(s) for which to obtain missing categories. |
A numeric vector (if x
is just one layer), or a named list of numeric vectors, one per layer in x
.
missingCats()
, missing.cases()
, droplevels()
, vignette("GRasters", package = "fasterRaster")
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) }
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) }
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
or GVector
, use mow(GRaster_to_unlink)
or mow(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
or GVector
, use mow("*")
.
To remove all rasters or all vectors in the GRASS cache, use mow("*", type = "rasters")
or mow("*", type = "vectors")
.
To remove all rasters or all vectors in the GRASS cache except for certain ones, use mow("*", unlinked = FALSE, keep = list(GRaster_to_keep, GVector_to_keep))
. You can combine this with the keep
argument to retain specific rasters or vectors. For example, you can use mow("*", unlinked = FALSE, type = "rasters", keep = list(GRaster_to_keep))
.
mow( x = "unlinked", pos = NULL, type = NULL, keep = NULL, verbose = TRUE, ask = TRUE )
mow( x = "unlinked", pos = NULL, type = NULL, keep = NULL, verbose = TRUE, ask = TRUE )
x |
Any of:
|
pos |
Either |
type |
Either |
keep |
Either |
verbose |
Logical: If |
ask |
Logical: If |
Invisibly returns a named vector with the number of rasters and vectors deleted.
if (grassStarted()) { # Setup madElev <- fastData("madElev") elev <- fast(madElev) mow(elev, ask = TRUE) # delete GRASS raster attached to `elev` }
if (grassStarted()) { # Setup madElev <- fastData("madElev") elev <- fast(madElev) mow(elev, ask = TRUE) # delete GRASS raster attached to `elev` }
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.
## S4 method for signature 'GRaster' nacell(x, warn = TRUE) ## S4 method for signature 'GRaster' nonnacell(x, warn = TRUE)
## S4 method for signature 'GRaster' nacell(x, warn = TRUE) ## S4 method for signature 'GRaster' nonnacell(x, warn = TRUE)
x |
A |
warn |
Logical: If |
A numeric value, one per raster layer in the input.
ncell()
, ncell3d()
, terra::ncell()
, dim()
, terra::dim()
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 }
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 }
names()
returns that names(s) of a GRaster
or of columns of a GVector
's data table'.
## 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
## 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
x |
A |
value |
Character: Name(s) to assign to the raster(s). |
names(value) <-
assigns a new name to the GRaster
or to the columns of a GVector
's data table.
Character vector.
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 }
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 }
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.
## S4 method for signature 'GVector' ngeom(x) ## S4 method for signature 'GVector' nsubgeom(x)
## S4 method for signature 'GVector' ngeom(x) ## S4 method for signature 'GVector' nsubgeom(x)
x |
A |
An integer.
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) }
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) }
This function reports the number of categories (levels) in a categorical GRaster
.
## S4 method for signature 'GRaster' nlevels(x)
## S4 method for signature 'GRaster' nlevels(x)
x |
A |
A named, numeric vector of integers. The values represent the number of categories (rows) that appear in the raster's levels table.
levels()
, terra::levels()
, droplevels()
, vignette("GRasters", package = "fasterRaster")
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) }
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) }
pairs()
generates a scatterplot between values of cells in each layer of a GRaster
against all the other layers.
## S4 method for signature 'GRaster' pairs(x, n = NULL, ...)
## S4 method for signature 'GRaster' pairs(x, n = NULL, ...)
x |
A |
n |
A numeric integer, integer, or |
... |
Arguments to send to
|
Nothing (creates a plot).
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 }
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
pcs(x)
pcs(x)
x |
A |
An object of class prcomp
.
princomp()
, terra::princomp()
, module i.pca
in GRASS
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) }
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) }
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.
## S4 method for signature 'GRaster,missing' plot(x, y, simplify = TRUE, ...) ## S4 method for signature 'GVector,missing' plot(x, y, maxGeoms = 10000, ...)
## S4 method for signature 'GRaster,missing' plot(x, y, simplify = TRUE, ...) ## S4 method for signature 'GVector,missing' plot(x, y, maxGeoms = 10000, ...)
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 |
Nothing (displays a raster or vector).
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) }
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) }
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.
## S4 method for signature 'GRaster' plotRGB(x, r = 1, g = 2, b = 3, a = NULL, simplify = TRUE, ...)
## S4 method for signature 'GRaster' plotRGB(x, r = 1, g = 2, b = 3, a = NULL, simplify = TRUE, ...)
x |
A |
r , g , b
|
Either a numeric integer or the |
a |
Either |
simplify |
Logical: If |
... |
Arguments to pass to |
Nothing (makes a plot).
terra::plotRGB()
, plot()
, compositeRGB()
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) }
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) }
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
and x1 * x2
;
Categorical predictors (i.e., categorical GRaster
s; see vignette("GRasters", package = "fasterRaster")
);
Two-way interactions between a categorical predictor and a scalar predictor; and
Two-way interactions between categorical predictors.
## S4 method for signature 'GRaster' predict(object, model, type = "response")
## S4 method for signature 'GRaster' predict(object, model, type = "response")
object |
A |
model |
An |
type |
Character: Type of prediction to make. This can be either |
A GRaster
.
terra::predict()
; stats::predict()
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) }
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) }
This function applies a principal component analysis to layers of a GRaster
.
## S4 method for signature 'GRaster' princomp(x, scale = TRUE, scores = FALSE)
## S4 method for signature 'GRaster' princomp(x, scale = TRUE, scores = FALSE)
x |
A |
scale |
Logical: If |
scores |
Logical: If |
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.
terra::princomp()
, terra::prcomp()
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) }
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) }
project()
changes the coordinate reference system (CRS) of a GRaster
or GVector
. It has three use cases:
x
is a GRaster
and y
is a GRaster
: x
will be projected to the CRS of y
and resampled to have the same resolution as y
. If argument align
is FALSE
, then it will also be cropped to the extent of y
.
x
is a GRaster
and y
is a GVector
or a CRS string (typically in Well-Known Text format): x
will be projected to the CRS specified by y
and resampled but not cropped.
x
is a GVector
and y
is a GRaster
, GVector
, or CRS string: The vector will be projected to the CRS of y
.
## 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)
## 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)
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 |
When projecting a raster, the "fallback" methods in GRASS module r.import
are actually used, even though the method
argument takes the strings specifying non-fallback methods. See the manual page for the r.import
GRASS module.
A GRaster
or GVector
.
terra::project()
, sf::st_transform()
, GRASS manual pages for modules r.proj
and v.proj
(see grassHelp("r.proj")
and grassHelp("v.proj")
)
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)) }
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)) }
The fasterRaster version of the rast()
function converts a GRaster
to a SpatRaster
(from the terra package).
## S4 method for signature 'GRaster' rast(x, mm = FALSE, ...)
## S4 method for signature 'GRaster' rast(x, mm = FALSE, ...)
x |
A |
mm |
Logical: If |
... |
Additional arguments to send to |
A SpatRaster
(terra package).
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 }
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 }
The rasterize()
function converts a GVector
into a GRaster
.
## S4 method for signature 'GVector,GRaster' rasterize(x, y, field = "", background = NA, by = NULL, verbose = TRUE)
## S4 method for signature 'GVector,GRaster' rasterize(x, y, field = "", background = NA, by = NULL, verbose = TRUE)
x |
A |
y |
A |
field |
Character: Name of a column in the data table of |
background |
Numeric or |
by |
Either |
verbose |
Logical: If |
A GRaster
.
terra::rasterize()
, GRASS module v.to.rast
(see grassHelp("v.to.rast")
)
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) }
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) }
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.
## S4 method for signature 'GVector' rbind(..., deparse.level = 1)
## S4 method for signature 'GVector' rbind(..., deparse.level = 1)
... |
One or more |
deparse.level |
See |
A GVector
.
colbind()
, addTable<-
, dropTable()
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 }
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 }
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()
.
## S4 method for signature 'GRaster,missing' regress(y, x, na.rm = FALSE)
## S4 method for signature 'GRaster,missing' regress(y, x, na.rm = FALSE)
y |
A multi-layer |
x |
Ignored. |
na.rm |
Logical: If |
A multi-layer GRaster
.
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) }
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) }
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.
## S4 method for signature 'GRaster' reorient(x, units = "degrees") ## S4 method for signature 'numeric' reorient(x, units = "degrees")
## S4 method for signature 'GRaster' reorient(x, units = "degrees") ## S4 method for signature 'numeric' reorient(x, units = "degrees")
x |
A numeric vector or a |
units |
Character: "Units" of values in |
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.
### 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) }
### 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) }
This function replaces NA
s in one or more data.table
, data.frame
, or matrix
columns, or in vectors, with a user-defined value.
## 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)
## 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)
x |
A |
replace |
A value of any atomic class (numeric, integer, character, Date, etc.): Value to to replace |
cols |
|
A data.table
, data.frame
, matrix
, or vector.
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
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 of a GRaster
:
res()
: 2-dimensional resolution (x and y).
res3d()
: 3-dimensional resolution (z, y, and z).
xres()
, yres()
, and zres()
: East-west resolution, north-south resolution, and top-bottom resolution.
## 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)
## 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)
x |
A |
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.
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 }
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 }
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.
## 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)
## 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)
x |
The |
y |
Either a |
method |
Character or
|
fallback |
Logical: If |
A GRaster
.
terra::resample()
, GRASS modules r.resample
and r.resamp.interp
(see grassHelp("
r.resample") and
grassHelp("r.resamp.interp
")')
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) }
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) }
rnormRast()
creates a raster with values drawn from a normal distribution.
## S4 method for signature 'GRaster' rnormRast(x, n = 1, mu = 0, sigma = 1, seed = NULL)
## S4 method for signature 'GRaster' rnormRast(x, n = 1, mu = 0, sigma = 1, seed = NULL)
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 |
A GRaster
.
rSpatialDepRast()
, fractalRast()
, runifRast()
, GRASS manual page for module r.random.surface
(see grassHelp("r.random.surface")
)
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) }
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) }
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.
## S4 method for signature 'GRaster' rSpatialDepRast( x, n = 1, mu = 0, sigma = 1, dist = 0, exponent = 1, delay = 0, seed = NULL )
## S4 method for signature 'GRaster' rSpatialDepRast( x, n = 1, mu = 0, sigma = 1, dist = 0, exponent = 1, delay = 0, seed = NULL )
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 |
A GRaster
.
rnormRast()
, fractalRast()
, runifRast()
, GRASS manual page for module r.random.surface
(see grassHelp("r.random.surface")
)
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) }
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) }
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
where is the elevation of the focal cell and
is the elevation of the ith grid cell.
## S4 method for signature 'GRaster' ruggedness(x)
## S4 method for signature 'GRaster' ruggedness(x)
x |
A |
A GRaster
.
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.
terrain()
, wetness()
, geomorphons()
if (grassStarted()) { # Setup library(terra) # Elevation raster madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) # Terrain ruggedness index: tri <- ruggedness(elev) plot(c(elev, tri)) # Topographic wetness index: twi <- wetness(elev) plot(c(elev, twi)) }
if (grassStarted()) { # Setup library(terra) # Elevation raster madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) # Terrain ruggedness index: tri <- ruggedness(elev) plot(c(elev, tri)) # Topographic wetness index: twi <- wetness(elev) plot(c(elev, twi)) }
runifRast()
creates a raster with values drawn from a uniform (flat) distribution.
## S4 method for signature 'GRaster' runifRast(x, n = 1, low = 0, high = 1, seed = NULL)
## S4 method for signature 'GRaster' runifRast(x, n = 1, low = 0, high = 1, seed = NULL)
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 |
A GRaster
.
rnormRast()
, rSpatialDepRast()
, fractalRast()
, GRASS manual page for module r.random.surface
(see grassHelp("r.random.surface")
)
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) }
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) }
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()
.
## S4 method for signature 'GRaster' rvoronoi(x, size = 100, seed = NULL) ## S4 method for signature 'GVector' rvoronoi(x, size = 100, seed = NULL)
## S4 method for signature 'GRaster' rvoronoi(x, size = 100, seed = NULL) ## S4 method for signature 'GVector' rvoronoi(x, size = 100, seed = NULL)
x |
A |
size |
Numeric integer or integer: Number of polygons. |
seed |
Numeric integer, integer, or |
A GVector
.
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) }
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) }
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()
.
## S4 method for signature 'GRaster' sampleRast( x, size, prop = FALSE, maskvalues = NA, updatevalue = NULL, test = FALSE, seed = NULL )
## S4 method for signature 'GRaster' sampleRast( x, size, prop = FALSE, maskvalues = NA, updatevalue = NULL, test = FALSE, seed = NULL )
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 |
|
A GRaster
.
spatSample()
; terra::spatSample()
, module r.random
in GRASS
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) }
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) }
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).
## 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)
## 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)
x |
A |
center |
Value depends on the function:
|
scale |
Value depends on the function:
|
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
.
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 }
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 }
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.
## S4 method for signature 'GRaster' segregate(x, classes = NULL, keep = FALSE, other = 0, bins = 100, digits = 3)
## S4 method for signature 'GRaster' segregate(x, classes = NULL, keep = FALSE, other = 0, bins = 100, digits = 3)
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 |
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.
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) }
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) }
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.
## S4 method for signature 'GRaster' selectRange(x, y)
## S4 method for signature 'GRaster' selectRange(x, y)
x |
A |
y |
A |
A GRaster
.
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) }
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) }
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.
seqToSQL(x, maxChar = 29900, sort = TRUE)
seqToSQL(x, maxChar = 29900, sort = TRUE)
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 |
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.
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)
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)
simplifyGeom()
reduces the number of vertices used to represent a vector (i.e., to save memory or disk space). There are several methods available.
## S4 method for signature 'GVector' simplifyGeom(x, tolerance = NULL, method = "VR", prop = 0.5)
## S4 method for signature 'GVector' simplifyGeom(x, tolerance = NULL, method = "VR", prop = 0.5)
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). |
A GVector
.
smoothGeom()
, geometry cleaning, terra::simplifyGeom()
, GRASS manual page for module v.generalize
(see grassHelp("v.generalize")
)
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") ) }
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") ) }
This function creates one or more rasters with sine waves in the north-south and east-west directions.
## 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 )
## 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 )
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 |
A GRaster
.
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) }
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) }
smoothGeom()
makes line segments of a vector appear less angular.
## S4 method for signature 'GVector' smoothGeom(x, method = "Hermite", dist = NULL, angle = 3)
## S4 method for signature 'GVector' smoothGeom(x, method = "Hermite", dist = NULL, angle = 3)
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. |
A GVector
.
simplifyGeom()
, terra::simplifyGeom()
, geometry cleaning, GRASS manual page for module v.generalize
(see grassHelp("v.generalize")
)
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") ) }
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") ) }
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.
## S4 method for signature 'GRaster' sources(x) ## S4 method for signature 'GVector' sources(x) ## S4 method for signature 'character' sources(x)
## S4 method for signature 'GRaster' sources(x) ## S4 method for signature 'GVector' sources(x) ## S4 method for signature 'character' sources(x)
x |
Either a |
Character.
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 }
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 }
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()
.
## 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 )
## 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 )
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 |
A data.frame
, data.table
, or GVector
.
sampleRast()
, terra::spatSample()
, module v.random
in GRASS
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) }
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) }
This function estimates the course of streams and rivers from an elevation raster. It is based on the GRASS module r.stream.extract
, where more details can be found (see grassHelp("r.stream.extract")
)
## S4 method for signature 'GRaster' streams( x, accumulation = NULL, depression = NULL, flowThreshold = 1, dirThreshold = 1, montgomery = 0, minLength = 1 )
## S4 method for signature 'GRaster' streams( x, accumulation = NULL, depression = NULL, flowThreshold = 1, dirThreshold = 1, montgomery = 0, minLength = 1 )
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). |
A GRaster
.
flow()
, flowPath()
, GRASS manual for module r.stream.extract
(see grassHelp("r.stream.extract")
)
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) }
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) }
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
.
## S4 method for signature 'GRaster' stretch(x, minv = 0, maxv = 255, minq = 0, maxq = 1, smin = NA, smax = NA)
## S4 method for signature 'GRaster' stretch(x, minv = 0, maxv = 255, minq = 0, maxq = 1, smin = NA, smax = NA)
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 |
A GRaster
.
terra::stretch()
and module r.rescale
in GRASS (not used on this function)
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 }
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()
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.
## S4 method for signature 'GRaster' subset(x, subset, negate = FALSE) ## S4 method for signature 'GVector' subset(x, subset, negate = FALSE)
## S4 method for signature 'GRaster' subset(x, subset, negate = FALSE) ## S4 method for signature 'GVector' subset(x, subset, negate = FALSE)
x |
A |
subset |
Numeric integer, integer, logical, or character: Indicates the layer(s) of a |
negate |
Logical: If |
A GRaster
or GVector
.
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
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 # Convert SpatVector to GVector dypsis <- fast(madDypsis) ### Retrieving GVector columns dypsis$species # Returns the column dypsis[[c("year", "species")]] # Returns a GRaster with these columns dypsis[ , c("year", "species")] # Same as above ### Subsetting GVector geometries # Subset first three geometries dypsis[1:3] dypsis[1:3, "species"] # Get geometries by data table condition dypsis[dypsis$species == "Dypsis betsimisarakae"] ### (Re)assigning GVector column values # New column dypsis$pi <- pi # Re-assign values dypsis$pi <- "pie" # Re-assign specific values dypsis$institutionCode[dypsis$institutionCode == "MO"] <- "Missouri Botanical Garden" }
This function replaces one or more user-specified values in a raster with other values. See classify()
for replacing ranges of values.
## S4 method for signature 'GRaster' subst(x, from, to, others = NULL, warn = TRUE)
## S4 method for signature 'GRaster' subst(x, from, to, others = NULL, warn = TRUE)
x |
A |
from , to
|
Vectors of numeric or character values. The value(s) in
|
others |
|
warn |
Logical: If |
A GRaster
.
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)) }
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)) }
The sun()
function calculates beam (direct), diffuse and ground reflected solar irradiation for a given day and set of topographic and atmospheric conditions. The function relies on the GRASS module r.sun
, the manual page for which contains a detailed explanation (see grassHelp("r.sun")
)
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 )
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 )
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 |
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)
terrain()
, horizonHeight()
, GRASS manual page for module r.sun
(see grassHelp("r.sun")
)
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 }
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 }
terrain()
calculates topographic indices, including slope, aspect, curvature, and partial slopes (slopes in the east-west or north-south directions).
## S4 method for signature 'GRaster' terrain( x, v = "slope", units = "degrees", undefinedAspect = NA, northIs0 = TRUE )
## S4 method for signature 'GRaster' terrain( x, v = "slope", units = "degrees", undefinedAspect = NA, northIs0 = TRUE )
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 |
A GRaster
with one or more layers.
terra::terrain()
, ruggedness()
, wetness()
, geomorphons()
, module r.slope.aspect
in GRASS
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) }
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) }
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()
.
## S4 method for signature 'GRaster' thinLines(x, iter = 200)
## S4 method for signature 'GRaster' thinLines(x, iter = 200)
x |
A |
iter |
Numeric integer: Number of iterations (default is 200). |
A GRaster
.
as.lines()
, GRASS manual page for module r.thin
(see grassHelp("r.thin")
)
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) }
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) }
This function thins a "points" GVector
so that it has no more than n
points per grid cell in a raster.
## S4 method for signature 'GVector,GRaster' thinPoints(x, y, n = 1)
## S4 method for signature 'GVector,GRaster' thinPoints(x, y, n = 1)
x |
A "points" |
y |
A |
n |
Integer or numeric integer: Maximum number of points to remain in a cell. The default is 1. |
A "points" GVector
.
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 ) }
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 ) }
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.
## S4 method for signature 'GRaster' tiles(x, n, overlap = 0, verbose = FALSE)
## S4 method for signature 'GRaster' tiles(x, n, overlap = 0, verbose = FALSE)
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 |
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.
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) }
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) }
GRaster
s and GVector
s can have 2-dimensional or 3-dimensional coordinates. This function returns the dimensions of the object.
## S4 method for signature 'GSpatial' topology(x)
## S4 method for signature 'GSpatial' topology(x)
x |
A |
Either "2D" or "3D".
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 }
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 }
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.
## S4 method for signature 'GRaster' trim(x, pad = 0)
## S4 method for signature 'GRaster' trim(x, pad = 0)
x |
A |
pad |
Numeric integer: Number of |
A GRaster
.
terra::trim()
, extend()
, and GRASS module g.region
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) }
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) }
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
).
## S4 method for signature 'GVector,GVector' union(x, y)
## S4 method for signature 'GVector,GVector' union(x, y)
x , y
|
|
A GVector
.
c()
, aggregate()
, crop()
, intersect()
, xor()
, erase()
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() }
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() }
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.
## S4 method for signature 'GRaster' update(object) ## S4 method for signature 'GVector' update(object)
## S4 method for signature 'GRaster' update(object) ## S4 method for signature 'GVector' update(object)
object |
A |
A GRaster
or GVector
.
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 }
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 }
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).
## S4 method for signature 'GVector' vect(x, ...) ## S4 method for signature 'GVector' st_as_sf(x)
## S4 method for signature 'GVector' vect(x, ...) ## S4 method for signature 'GVector' st_as_sf(x)
x |
A |
... |
Additional arguments to send to |
vect()
returns a SpatVector
(terra package), and st_as_sf()
returns an sf
vector (sf package).
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) }
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) }
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.
## 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 )
## 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 )
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 |
A GRaster
.
GRASS manual page for module i.vi
(see grassHelp("i.vi")
)
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) }
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) }
vegIndex()
. A near-comprehensive table of indices can be found on the Index Database: A Database for Remote Sensing Indices.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.
An object of class data.frame
.
### 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)
### 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)
This function creates a Voronoi tessellation from a set of spatial points or polygons.
## S4 method for signature 'GVector' voronoi(x, buffer = 0)
## S4 method for signature 'GVector' voronoi(x, buffer = 0)
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. |
A GVector
.
terra::voronoi()
, sf::st_voronoi()
, module v.voronoi
in GRASS
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) }
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) }
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.
## S4 method for signature 'GRaster' wetness(x)
## S4 method for signature 'GRaster' wetness(x)
x |
A |
A GRaster
.
terrain()
, ruggedness()
, geomorphons()
, GRASS manual for module r.topidx
(see grassHelp("r.topidx")
)
if (grassStarted()) { # Setup library(terra) # Elevation raster madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) # Terrain ruggedness index: tri <- ruggedness(elev) plot(c(elev, tri)) # Topographic wetness index: twi <- wetness(elev) plot(c(elev, twi)) }
if (grassStarted()) { # Setup library(terra) # Elevation raster madElev <- fastData("madElev") # Convert to GRaster: elev <- fast(madElev) # Terrain ruggedness index: tri <- ruggedness(elev) plot(c(elev, tri)) # Topographic wetness index: twi <- wetness(elev) plot(c(elev, twi)) }
This function saves a GRaster
to disk directly from a GRASS session. It is faster than using rast()
, then saving the output of that to disk (because rast()
actually save the raster to disk, anyway).
The function will attempt to ascertain the file type to be ascertained from the file extension, but you can specify the format using the format
argument (see entry for ...
). You can see a list of supported formats by simply using this function with no arguments, as in writeRaster()
, or by consulting the online help page for the GRASS module r.out.gdal
(see grassHelp("r.out.gdal")
). Only the GeoTIFF
file format is guaranteed to work for multi-layered rasters.
The function will attempt to 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.
## 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)
## 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)
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:
|
A GRaster
(invisibly). A raster is also saved to disk.
terra::writeRaster()
, GRASS module r.out.gdal
(see grassHelp("r.out.gdal")
)
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 }
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 }
This function saves a GVector
to disk directly from a GRASS session.
By default, files will be of OGC GeoPackage format (extension ".gpkg
"), but this can be changed with the format
argument. You can see a list of supported formats by simply using this function with no arguments, as in writeVector()
, or by consulting the online help page for GRASS module v.out.ogr
(see grassHelp("v.out.ogr")
).
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.
## S4 method for signature 'GVector,character' writeVector( x, filename, overwrite = FALSE, format = NULL, attachTable = TRUE, ... ) ## S4 method for signature 'missing,missing' writeVector(x, filename)
## S4 method for signature 'GVector,character' writeVector( x, filename, overwrite = FALSE, format = NULL, attachTable = TRUE, ... ) ## S4 method for signature 'missing,missing' writeVector(x, filename)
x |
A |
filename |
Character: Path and file name. |
overwrite |
Logical: If |
format |
Character or
|
attachTable |
Logical: If |
... |
Additional arguments to send to GRASS module |
Invisibly returns a GRaster
(the input, x
). Also saves the vector to disk.
terra::writeVector()
, sf::st_write()
, GRASS module v.out.ogr
(see grassHelp("v.out.ogr")
)
terra::writeVector()
, the GRASS module manual page for v.out.ogr
(see grassHelp("v.out.ogr")
)
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) }
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) }
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
.
## S4 method for signature 'GVector,GVector' xor(x, y)
## S4 method for signature 'GVector,GVector' xor(x, y)
x , y
|
|
A GVector
.
crop()
, intersect()
, union()
, erase()
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() }
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() }
Function zonal()
calculates statistics (mean, sum, etc.) on cells of a GRaster
by "zones" created by cells of another GRaster
or GVector
.
## S4 method for signature 'GRaster,ANY' zonal(x, z, fun = "mean", probs = 0.5)
## S4 method for signature 'GRaster,ANY' zonal(x, z, fun = "mean", probs = 0.5)
x |
A |
z |
A
|
fun |
Character vector: Name of the function(s) to summarize
|
probs |
Numeric: Quantile at which to calculate |
A data.frame
or data.table
.
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") }
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") }
This function calculates geographic statistics for each set of cells in an integer
or factor
GRaster
. Statistics include:
Area
Perimeter length
"Compact square" statistic:
"Compact circle" statistic: where P is the perimeter length and A the area.
fractal dimension: where P is perimeter length and A is area.
The average x- and y-coordinates of each zone.
## S4 method for signature 'GRaster' zonalGeog(x, unit = "meters")
## S4 method for signature 'GRaster' zonalGeog(x, unit = "meters")
x |
A |
unit |
Character: Units of the output. Any of:
Partial matching is used and case is ignored. |
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.
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) }
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) }