Skip to content

Commit

Permalink
new function to calculate the percentage of change between rasters
Browse files Browse the repository at this point in the history
  • Loading branch information
flaviomoc committed Aug 26, 2024
1 parent 8047f6f commit 13db35e
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by roxygen2: do not edit by hand

export(area.calc)
export(differ.rast)
export(dist.centroids)
export(load.data)
export(spat.alpha)
Expand Down
49 changes: 49 additions & 0 deletions R/diff_rast.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#' Difference between raster objects
#'
#' @param r1 A SpatRaster object.
#' @param r2 A SpatRaster object.
#' @param perc Boolean. Default is TRUE to calculate the percentage
#' of change between r1 and r2. FALSE gives the absolute number
#' instead.
#' @param filename Character. Save results if a name is provided.
#'
#' @return A SpatRaster object with the difference between
#' r1 and r2.
#' @export
#'
#' @examples
#' \donttest{
#' library(terra)
#' rich1 <- terra::rast(system.file("extdata", "rich_ref.tif",
#' package = "divraster"))
#' rich2 <- terra::rast(system.file("extdata", "rich_fut.tif",
#' package = "divraster"))
#' differ.rast(rich1, rich2)
#' }
differ.rast <- function(r1, r2, perc = TRUE, filename = "") {
# Check that the rasters have the same resolution and extent
if (!terra::compareGeom(r1, r2, stopOnError = FALSE)) {
stop("r1 and r2 must have the same extent and resolution")
}

# Calculate the difference
diff <- r2 - r1 # Ensure this returns a raster

# Calculate percentage difference if requested
if (perc) {
# Calculate percentage difference
perc_diff <- (diff / r1) * 100
perc_diff[is.na(r1) | r1 == 0] <- NA # Handle NA and zero values properly
names(perc_diff) <- "Percentage Difference"
diff <- perc_diff
} else {
names(diff) <- "Absolute Difference"
}

# Save the result if a filename is provided
if (filename != "") {
terra::writeRaster(diff, filename = filename, overwrite = TRUE)
}

return(diff)
}
Binary file added inst/extdata/rich_fut.tif
Binary file not shown.
Binary file added inst/extdata/rich_ref.tif
Binary file not shown.
36 changes: 36 additions & 0 deletions man/differ.rast.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 13db35e

Please sign in to comment.