differ.rast {divraster} | R Documentation |
Calculate Absolute or Percentage Difference Between SpatRaster Objects
Description
Computes the difference between two SpatRaster
objects, either as an absolute value
or as a percentage of change relative to the first raster (r1
).
This function is commonly used to assess changes in spatial patterns, such as
shifts in species richness or environmental variables over time or between scenarios.
Usage
differ.rast(r1, r2, perc = TRUE, filename = "")
Arguments
r1 |
A |
r2 |
A |
perc |
Logical (default is |
filename |
Character string. Optional path and filename to save the resulting
|
Details
This function performs a cell-wise subtraction (r2 - r1
).
For percentage difference, the formula used is
((r2 - r1) / r1) * 100
. Cells wherer1
isNA
or0
will result inNA
in the outputSpatRaster
for percentage calculations, to avoid division by zero or meaningless percentages.It is crucial that
r1
andr2
are aligned spatially (same extent, resolution, and Coordinate Reference System - CRS) and have the same number of layers, with corresponding layers representing the same variable or species.
Value
A SpatRaster
object containing the calculated differences.
If
perc = TRUE
, the layer name will be "Percentage_Difference".If
perc = FALSE
, the layer name will be "Absolute_Difference".
The output SpatRaster
will have the same dimensions, resolution, and CRS as
the input rasters.
Examples
library(terra)
# Load rasters
rich1 <- terra::rast(system.file("extdata", "rich_ref.tif",
package = "divraster"))
rich2 <- terra::rast(system.file("extdata", "rich_fut.tif",
package = "divraster"))
# Calculate absolute difference in richness
abs_diff_rast <- differ.rast(rich1, rich2, perc = FALSE)
abs_diff_rast
plot(abs_diff_rast, main = "Absolute Difference in Richness")
# Calculate percentage difference in richness
perc_diff_rast <- differ.rast(rich1, rich2, perc = TRUE)
perc_diff_rast
plot(perc_diff_rast, main = "Percentage Difference in Richness")