| Title: | An R Package for Analyzing and Comparing Habitat Changes |
|---|---|
| Description: | An R package for analyzing and comparing habitat and species distributions changes. Ideal for students, ecologists, environmental researchers, and conservation planners. |
| Authors: | Saman Ghasemian Sorboni [aut, cre], Mehrdad Hadipour [aut] |
| Maintainer: | Saman Ghasemian Sorboni <[email protected]> |
| License: | GPL-3 + file LICENSE |
| Version: | 1.6-13 |
| Built: | 2026-05-16 08:30:31 UTC |
| Source: | https://github.com/samanghs/habitat |
This function generates a frequency table of raster values. It calculates the frequency of each unique value in the raster, providing a summary of the distribution of values.
frequency(raster)frequency(raster)
raster |
A SpatRaster object. This represents the raster dataset from which the frequency table will be generated. |
The function is designed to take a raster dataset and create a frequency table that summarizes the distribution of values within the raster. This is useful for understanding the composition and variability of the raster data.
A data frame containing the frequency of each raster value. The data frame includes two columns: Value, which represents the unique values in the raster, and Frequency, which indicates the number of times each value occurs.
## Not run: # Create a sample raster dataset with random values between 1 and 5 raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(1:5, 100, replace = TRUE) ) # Generate the frequency table for the raster values freq_table <- terra::frequency(raster) # Display the frequency table print(freq_table) ## End(Not run)## Not run: # Create a sample raster dataset with random values between 1 and 5 raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(1:5, 100, replace = TRUE) ) # Generate the frequency table for the raster values freq_table <- terra::frequency(raster) # Display the frequency table print(freq_table) ## End(Not run)
Summarizes the multidimensional dataset across a specific dimension (e.g., calculating the average habitat suitability over time). This is the second step in a sequence of functions to analyze habitat trends.
hb_agg_md_raster(multidimensional_raster, fun = mean)hb_agg_md_raster(multidimensional_raster, fun = mean)
multidimensional_raster |
A |
fun |
A function to apply for aggregation (e.g., mean, sum). |
A SpatRaster object representing the aggregated raster.
## Not run: # Same synthetic setup as in multidimensional raster_files <- list(r1, r2) time_points <- c(2022, 2023) multidimensional_raster <- hb_multiD_raster(raster_files, time_points) aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)## Not run: # Same synthetic setup as in multidimensional raster_files <- list(r1, r2) time_points <- c(2022, 2023) multidimensional_raster <- hb_multiD_raster(raster_files, time_points) aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)
Analyzes the range of suitable habitat based on a given threshold and provides statistics and a histogram plot.
hb_an_habitat(x1, x2, threshold = 0.5)hb_an_habitat(x1, x2, threshold = 0.5)
x1 |
Path to the input raster file (e.g., Elevation, NDVI). |
x2 |
Path to the habitat suitability raster file (e.g., ensemble map). |
threshold |
Numeric value for the presence probability threshold. Default is 0.5. |
Calculates the range of suitable habitat areas using pre-aligned raster files.
A list containing the range statistics and the histogram plot.
## Not run: # Create synthetic rasters or load it: "x1" and "x2" # Analyze habitat with threshold result <- hb_an_habitat(x1, x2, threshold = 0.5) # Print results print(result$statistics) print(result$plot) ## End(Not run)## Not run: # Create synthetic rasters or load it: "x1" and "x2" # Analyze habitat with threshold result <- hb_an_habitat(x1, x2, threshold = 0.5) # Print results print(result$statistics) print(result$plot) ## End(Not run)
Applies statistical functions to identify trends, anomalies, or patterns in habitat changes. This is the third step in a sequence of functions to analyze habitat trends.
hb_analyze_changes(multidimensional_raster, fun = trend)hb_analyze_changes(multidimensional_raster, fun = trend)
multidimensional_raster |
A |
fun |
A function to compute the statistical summary (e.g., trend, anomaly detection). |
A data frame containing the statistical summaries.
## Not run: raster_files <- list(r1, r2) time_points <- c(2022, 2023) multidimensional_raster <- hb_multiD_raster(raster_files, time_points) aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) # NOTE: Depending on your dataset, calculations may take time trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)## Not run: raster_files <- list(r1, r2) time_points <- c(2022, 2023) multidimensional_raster <- hb_multiD_raster(raster_files, time_points) aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) # NOTE: Depending on your dataset, calculations may take time trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)
Converts a continuous raster dataset into a binary map based on a specified threshold. Values in the raster that are greater than the threshold are converted to TRUE, while values less than or equal to the threshold are converted to FALSE.
hb_binary(x, th)hb_binary(x, th)
x |
A RasterLayer or SpatRaster object representing the continuous raster dataset to be converted. |
th |
A numeric threshold value between 0 and 1, determining the cutoff point for converting values to |
This function is designed to convert a continuous raster dataset into a binary map. This is particularly useful for applications requiring binary classification of data, such as presence/absence mapping or suitability analysis.
A binary RasterLayer or SpatRaster where values greater than the specified threshold are TRUE, and values less than or equal to the threshold are FALSE.
## Not run: # Example usage with a SpatRaster object # Create a sample raster dataset with random values r <- terra::rast(nrows = 10, ncols = 10, vals = runif(100)) # Convert the raster to a binary map using a threshold of 0.5 binary_map <- hb_binary(r, th = 0.5) # Plot the resulting binary map plot(binary_map, main = "Binary Map (Threshold = 0.5)") ## End(Not run)## Not run: # Example usage with a SpatRaster object # Create a sample raster dataset with random values r <- terra::rast(nrows = 10, ncols = 10, vals = runif(100)) # Convert the raster to a binary map using a threshold of 0.5 binary_map <- hb_binary(r, th = 0.5) # Plot the resulting binary map plot(binary_map, main = "Binary Map (Threshold = 0.5)") ## End(Not run)
Calculates the suitable and unsuitable areas in hectares, square kilometers, and square meters from a binary raster.
hb_cal_area(binary_raster)hb_cal_area(binary_raster)
binary_raster |
A SpatRaster object representing the binary raster with suitable (1/TRUE) and unsuitable (0/FALSE) areas. |
This function calculates the total area of suitable and unsuitable regions in a binary raster and prints the results in hectares, square kilometers, and square meters.
None. The results are printed in the console.
## Not run: # Example usage with a binary SpatRaster object # Create a sample binary raster binary_raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(c(0, 1), 100, replace = TRUE) ) # Calculate and print the suitable and unsuitable areas hb_cal_area(binary_raster) ## End(Not run)## Not run: # Example usage with a binary SpatRaster object # Create a sample binary raster binary_raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(c(0, 1), 100, replace = TRUE) ) # Calculate and print the suitable and unsuitable areas hb_cal_area(binary_raster) ## End(Not run)
Compares two binary raster files and generates a new raster highlighting areas of gain, loss, stability, and absence. This function is specifically designed for comparing habitat changes between two time points or scenarios.
hb_changes(raster1, raster2)hb_changes(raster1, raster2)
raster1 |
A SpatRaster or RasterLayer object representing the first habitat map. |
raster2 |
A SpatRaster or RasterLayer object representing the second habitat map. |
hb_changes function ensures both input rasters are in the same CRS and extent, computes the differences, and generates a new raster with categories for gain (green), loss (red), stability (yellow), and absence (gray). It is useful for ecological and environmental studies to visualize how habitats have changed over time or under different conditions.
A SpatRaster object representing the habitat changes.
## Not run: # Create two sample rasters or load it: "r1" and "r2" # Convert to binary raster1_binary <- hb_binary(r1, th = 0.5) raster2_binary <- hb_binary(r2, th = 0.5) # Calculate changes changes_raster <- hb_changes(raster1_binary, raster2_binary) # Plot changes hb_plot_changes(changes_raster) ## End(Not run)## Not run: # Create two sample rasters or load it: "r1" and "r2" # Convert to binary raster1_binary <- hb_binary(r1, th = 0.5) raster2_binary <- hb_binary(r2, th = 0.5) # Calculate changes changes_raster <- hb_changes(raster1_binary, raster2_binary) # Plot changes hb_plot_changes(changes_raster) ## End(Not run)
Combines two or more rasters into a single ensemble map using either majority-based or statistical methods.
hb_ensemble( rasters, method = c("majority", "weighted_majority", "mean", "weighted_mean"), threshold = NULL, weights = NULL, na_rm = TRUE )hb_ensemble( rasters, method = c("majority", "weighted_majority", "mean", "weighted_mean"), threshold = NULL, weights = NULL, na_rm = TRUE )
rasters |
A list of SpatRaster or RasterLayer objects. |
method |
Character. One of:
|
threshold |
Numeric or |
weights |
Numeric vector of weights (same length as |
na_rm |
Logical. Remove NAs in calculations. Default |
Majority methods first binarize input rasters using the given threshold, then:
"majority": cells with > 50\
"weighted_majority": uses weighted sum of presences, applies cutoff of sum(weights)/2.
Statistical methods operate directly on continuous values:
"mean": cellwise unweighted mean.
"weighted_mean": cellwise weighted mean.
All rasters are aligned in CRS, resolution, and extent before computation.
A SpatRaster of the ensemble habitat suitability map.
## Not run: library(terra) r1 <- rast(matrix(runif(100, 0, 1), 10, 10)) r2 <- rast(matrix(runif(100, 0, 1), 10, 10)) r3 <- rast(matrix(runif(100, 0, 1), 10, 10)) # Unweighted mean ens_mean <- hb_ensemble(list(r1, r2, r3), method = "mean") # Weighted majority with threshold 0.6 ens_wmaj <- hb_ensemble(list(r1, r2, r3), method = "weighted_majority", threshold = 0.6, weights = c(0.5, 0.3, 0.2)) ## End(Not run)## Not run: library(terra) r1 <- rast(matrix(runif(100, 0, 1), 10, 10)) r2 <- rast(matrix(runif(100, 0, 1), 10, 10)) r3 <- rast(matrix(runif(100, 0, 1), 10, 10)) # Unweighted mean ens_mean <- hb_ensemble(list(r1, r2, r3), method = "mean") # Weighted majority with threshold 0.6 ens_wmaj <- hb_ensemble(list(r1, r2, r3), method = "weighted_majority", threshold = 0.6, weights = c(0.5, 0.3, 0.2)) ## End(Not run)
Computes descriptive statistics and plots a histogram of an environmental raster (e.g., elevation, slope) at species presence locations defined by a binary/suitability raster and a threshold. This wraps the common workflow of masking the environmental layer by presence, extracting values, summarizing them, and visualizing their distribution.
hb_env_at_presence( env_raster, suit_raster, threshold = 0.5, mask_geom = NULL, plot = TRUE, breaks = NULL, col = "lightgray", border = NA, main = "Environmental values at presence locations", xlab = "Environmental value", ylab = "Frequency", na_rm = TRUE )hb_env_at_presence( env_raster, suit_raster, threshold = 0.5, mask_geom = NULL, plot = TRUE, breaks = NULL, col = "lightgray", border = NA, main = "Environmental values at presence locations", xlab = "Environmental value", ylab = "Frequency", na_rm = TRUE )
env_raster |
A SpatRaster (preferred) or RasterLayer of the environmental variable (e.g., elevation in meters, slope in degrees). |
suit_raster |
A SpatRaster or RasterLayer representing species suitability or
presence probability. If already binary (0/1), set |
threshold |
Numeric or NULL. Threshold applied to |
mask_geom |
Optional SpatVector or SpatRaster mask/crop geometry (e.g., a border).
If provided, |
plot |
Logical. If TRUE, a histogram is plotted immediately. |
breaks |
Integer or vector. Breaks passed to |
col |
Character. Fill color for the histogram bars. Default |
border |
Character. Border color for the histogram bars. Default |
main |
Character. Plot title. Default |
xlab |
Character. X-axis label. Default |
ylab |
Character. Y-axis label. Default |
na_rm |
Logical. Whether to remove NA values in summaries. Default |
The function aligns CRS and geometry between env_raster and suit_raster
and uses nearest-neighbor methods for reprojection/resampling to preserve binary
presence masks derived from the suitability raster. Presence cells are defined as:
if threshold is numeric: suit_raster >= threshold
if threshold is NULL: suit_raster > 0
The histogram is drawn with base R hist() for speed and simplicity. Returned
statistics include Min, 1st Qu., Median, Mean, 3rd Qu., Max, SD, and N.
A named list with:
summary: a data.frame with Min, Q1, Median, Mean, Q3, Max, SD, N
values: a numeric vector of extracted environmental values at presence cells
presence_mask: the SpatRaster (0/1) presence mask used for extraction
## Not run: env <- rast(system.file("ex/elev.tif", package = "terra")) suit <- env / max(values(env), na.rm = TRUE) # fake suitability 0..1 # Analyze elevation values where suitability >= 0.5 and plot histogram res <- hb_env_at_presence( env_raster = env, suit_raster = suit, threshold = 0.5, plot = TRUE, col = "lightblue", main = "Elevation at presence (>= 0.5)", xlab = "Elevation (m)" ) res$summary ## End(Not run)## Not run: env <- rast(system.file("ex/elev.tif", package = "terra")) suit <- env / max(values(env), na.rm = TRUE) # fake suitability 0..1 # Analyze elevation values where suitability >= 0.5 and plot histogram res <- hb_env_at_presence( env_raster = env, suit_raster = suit, threshold = 0.5, plot = TRUE, col = "lightblue", main = "Elevation at presence (>= 0.5)", xlab = "Elevation (m)" ) res$summary ## End(Not run)
Removes a specified value from binarized raster or vector data.
hb_exclude_value(data, exclude_value)hb_exclude_value(data, exclude_value)
data |
A binarized raster (SpatRaster) or vector (SpatVector) object. |
exclude_value |
The value to exclude (e.g., FALSE or 0). |
A filtered raster or vector object with the specified value removed.
## Not run: # Create a sample binary raster # Exclude the specified value (e.g., 0) filtered_data <- hb_exclude_value(raster_data, exclude_value = 0) plot(filtered_data) # Example with a SpatVector coords <- matrix(runif(20), ncol = 2) polygon_data <- terra::vect(coords, type = "polygons") filtered_polygon <- hb_exclude_value(polygon_data, exclude_value = 0) plot(filtered_polygon) ## End(Not run)## Not run: # Create a sample binary raster # Exclude the specified value (e.g., 0) filtered_data <- hb_exclude_value(raster_data, exclude_value = 0) plot(filtered_data) # Example with a SpatVector coords <- matrix(runif(20), ncol = 2) polygon_data <- terra::vect(coords, type = "polygons") filtered_polygon <- hb_exclude_value(polygon_data, exclude_value = 0) plot(filtered_polygon) ## End(Not run)
Exports habitat change metrics to a CSV file. The habitat change metrics are extracted from the provided result list and saved as a CSV file at the specified file path.
hb_exp_csv(result, file_path)hb_exp_csv(result, file_path)
result |
A list containing the habitat change metrics. This list should include a component named |
file_path |
The file path where the CSV file will be saved. The path should include the desired file name and the |
Designed to facilitate the export of habitat change metrics to a CSV file, making it easier to save analysis results in a format that can be readily shared and imported into other software for further analysis.
None. This function is used for its side effect of writing the data to a CSV file.
## Not run: # Create a sample result list with habitat change metrics result <- list( Compt.By.Models = data.frame( Model = c("Model1", "Model2"), Metric1 = c(0.1, 0.2), Metric2 = c(0.3, 0.4) ) ) # Export the habitat change metrics to a CSV file hb_exp_csv(result, tempfile(fileext = ".csv")) ## End(Not run)## Not run: # Create a sample result list with habitat change metrics result <- list( Compt.By.Models = data.frame( Model = c("Model1", "Model2"), Metric1 = c(0.1, 0.2), Metric2 = c(0.3, 0.4) ) ) # Export the habitat change metrics to a CSV file hb_exp_csv(result, tempfile(fileext = ".csv")) ## End(Not run)
Exports a raster to a specified file format (.tif, .png, or .jpg).
hb_exp_raster(raster_data, file_path)hb_exp_raster(raster_data, file_path)
raster_data |
A raster (SpatRaster) object to be exported. |
file_path |
The file path where the raster will be saved. The extension should be .tif, .png, or .jpg. |
None. This function is used for its side effect of writing the raster to a file.
## Not run: # Create a sample raster or load: "raster_data" # Export the raster to various formats (saved to temp files) hb_exp_raster(raster_data, tempfile(fileext = ".tif")) hb_exp_raster(raster_data, tempfile(fileext = ".png")) hb_exp_raster(raster_data, tempfile(fileext = ".jpg")) ## End(Not run)## Not run: # Create a sample raster or load: "raster_data" # Export the raster to various formats (saved to temp files) hb_exp_raster(raster_data, tempfile(fileext = ".tif")) hb_exp_raster(raster_data, tempfile(fileext = ".png")) hb_exp_raster(raster_data, tempfile(fileext = ".jpg")) ## End(Not run)
Exports habitat change metrics to a TXT file. The habitat change metrics are extracted from the provided result list and saved as a TXT file at the specified file path.
hb_exp_txt(result, file_path)hb_exp_txt(result, file_path)
result |
A list containing the habitat change metrics. This list should include a component named |
file_path |
The file path where the TXT file will be saved. The path should include the desired file name and the |
Designed to facilitate the export of habitat change metrics to a TXT file, making it easier to save analysis results in a text format that can be readily shared and imported into other software for further analysis.
None. This function is used for its side effect of writing the data to a TXT file.
## Not run: # Create a sample result list with habitat change metrics result <- list( Compt.By.Models = data.frame( Model = c("Model1", "Model2"), Metric1 = c(0.1, 0.2), Metric2 = c(0.3, 0.4) ) ) # Export the habitat change metrics to a TXT file hb_exp_txt(result, tempfile(fileext = ".txt")) ## End(Not run)## Not run: # Create a sample result list with habitat change metrics result <- list( Compt.By.Models = data.frame( Model = c("Model1", "Model2"), Metric1 = c(0.1, 0.2), Metric2 = c(0.3, 0.4) ) ) # Export the habitat change metrics to a TXT file hb_exp_txt(result, tempfile(fileext = ".txt")) ## End(Not run)
Extracts evaluation metrics including threshold, sensitivity, specificity, TSS, MCC, F1, Kappa, NMI, PHI, PPV, NPV, CCR, MCR, Omission, Commission, and Prevalence from a trained sdm model.
hb_ext_eval(sdm_model)hb_ext_eval(sdm_model)
sdm_model |
An sdmModels object generated by the sdm function. |
A data frame with evaluation metrics.
## Not run: # Assume that the user has already trained their model and wants to extract the- # threshold value based on metrics such as sensitivity (sp), specificity (se), max(sp + se), # kappa, positive predictive value (ppv), negative predictive value (npv), # normalized mutual information (nmi), correct classification rate (ccr), prevalence, # and specific percentages (P10, P5, P1, P0). library(sdm) # sdm_model <- trained_model_object # Extract evaluation metrics eval_metrics <- hb_ext_eval(sdm_model) print(eval_metrics) ## End(Not run)## Not run: # Assume that the user has already trained their model and wants to extract the- # threshold value based on metrics such as sensitivity (sp), specificity (se), max(sp + se), # kappa, positive predictive value (ppv), negative predictive value (npv), # normalized mutual information (nmi), correct classification rate (ccr), prevalence, # and specific percentages (P10, P5, P1, P0). library(sdm) # sdm_model <- trained_model_object # Extract evaluation metrics eval_metrics <- hb_ext_eval(sdm_model) print(eval_metrics) ## End(Not run)
Generates a frequency table of raster values, calculating the frequency of each unique value in the raster and providing a summary of the distribution of values.
hb_frequency(raster)hb_frequency(raster)
raster |
A SpatRaster object representing the raster dataset from which the frequency table will be generated. |
Designed to create a frequency table that summarizes the distribution of values within a raster dataset, this function is useful for understanding the composition and variability of the raster data.
A data frame containing the frequency of each raster value. The data frame includes two columns: Value, representing the unique values in the raster, and Frequency, indicating the number of times each value occurs.
## Not run: # Create a sample raster dataset with random values between 1 and 5 raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(1:5, 100, replace = TRUE) ) # Generate the frequency table for the raster values freq_table <- hb_frequency(raster) # Display the frequency table print(freq_table) ## End(Not run)## Not run: # Create a sample raster dataset with random values between 1 and 5 raster <- terra::rast( nrows = 10, ncols = 10, vals = sample(1:5, 100, replace = TRUE) ) # Generate the frequency table for the raster values freq_table <- hb_frequency(raster) # Display the frequency table print(freq_table) ## End(Not run)
Loads a shapefile and ensures it is ready for compatibility with raster operations, such as CRS, extent, clipping, masking, and resolution modifications.
hb_load_shp(file_path)hb_load_shp(file_path)
file_path |
A character string specifying the path to the shapefile. |
Reads a shapefile from the specified path and prepares it for compatibility with raster operations by aligning its CRS and extent.
An sf object containing the shapefile data.
## Not run: # Create a temporary shapefile or load it with sf package library(sf) pts <- data.frame( id = 1:3, x = c(0, 1, 2), y = c(0, 1, 2) ) sf_obj <- st_as_sf(pts, coords = c("x", "y"), crs = 4326) shp_path <- tempfile(fileext = ".shp") st_write(sf_obj, shp_path, quiet = TRUE) # Load and prepare the shapefile shapefile_data <- hb_load_shp(shp_path) # Check CRS and extent print(st_crs(shapefile_data)) print(st_bbox(shapefile_data)) ## End(Not run)## Not run: # Create a temporary shapefile or load it with sf package library(sf) pts <- data.frame( id = 1:3, x = c(0, 1, 2), y = c(0, 1, 2) ) sf_obj <- st_as_sf(pts, coords = c("x", "y"), crs = 4326) shp_path <- tempfile(fileext = ".shp") st_write(sf_obj, shp_path, quiet = TRUE) # Load and prepare the shapefile shapefile_data <- hb_load_shp(shp_path) # Check CRS and extent print(st_crs(shapefile_data)) print(st_bbox(shapefile_data)) ## End(Not run)
Merges two or more rasters into a single raster file. If you encounter any issues with RasterLayer objects, use the spat_to_raster() function to convert them.
hb_merge(raster_list, output_path = NULL)hb_merge(raster_list, output_path = NULL)
raster_list |
A list of |
output_path |
A character string representing the file path to save the merged raster. If |
A RasterLayer object representing the merged raster.
## Not run: # Create two sample rasters or load it: "raster1" and "raster2" # Merge rasters (two or more), optionally saving to a file merged_raster <- hb_merge(list(raster1, raster2), tempfile(fileext = ".tif")) # NOTE: 'RasterLayer' issues? Use the spat_to_raster() function raster1_rl <- spat_to_raster(raster1) raster2_rl <- spat_to_raster(raster2) # Plot the merged raster plot(merged_raster) ## End(Not run)## Not run: # Create two sample rasters or load it: "raster1" and "raster2" # Merge rasters (two or more), optionally saving to a file merged_raster <- hb_merge(list(raster1, raster2), tempfile(fileext = ".tif")) # NOTE: 'RasterLayer' issues? Use the spat_to_raster() function raster1_rl <- spat_to_raster(raster1) raster2_rl <- spat_to_raster(raster2) # Plot the merged raster plot(merged_raster) ## End(Not run)
Modifies the CRS, extent, resolution, and applies crop and mask operations to a raster, providing a flexible method for adjusting the spatial parameters of a raster dataset.
hb_modify_raster( raster, crs = NULL, extent = NULL, resolution = NULL, crop_extent = NULL, mask = NULL )hb_modify_raster( raster, crs = NULL, extent = NULL, resolution = NULL, crop_extent = NULL, mask = NULL )
raster |
A SpatRaster object to be modified. Represents the raster dataset undergoing modifications. |
crs |
Optional. A character string specifying the new Coordinate Reference System (CRS) (e.g., "EPSG:4326"). If provided, the raster will be reprojected to this CRS. |
extent |
Optional. A numeric vector of four values specifying the new extent (xmin, xmax, ymin, ymax). If provided, the extent of the raster will be modified accordingly. |
resolution |
Optional. A numeric value or a vector of two numeric values specifying the new resolution. If provided, the raster will be resampled to this resolution. |
crop_extent |
Optional. A SpatExtent object or numeric vector specifying the extent to crop to. If provided, the raster will be cropped to this extent. |
mask |
Optional. A SpatRaster object to be used as a mask. If provided, the raster will be masked by this raster. |
Designed to provide a comprehensive set of modifications to a raster dataset, including changing the CRS, adjusting the extent, resampling the resolution, cropping to a specified extent, and applying a mask. These modifications are useful for preparing raster data for analysis, visualization, or integration with other spatial datasets.
A modified SpatRaster object with the specified modifications applied.
## Not run: # Create sample raster datasets or load: "r1" and "r2" # Modify the CRS and extent of the first raster modified_r1 <- hb_modify_raster(r1, crs = "EPSG:4326", extent = c(0, 1000, 0, 1000)) plot(modified_r1, main = "Modified Raster (CRS and Extent)") # Modify the CRS, extent, and crop the second raster modified_r2 <- hb_modify_raster(r2, crs = "EPSG:4326", extent = c(0, 1000, 0, 1000), crop_extent = modified_r1) plot(modified_r2, main = "Modified Raster (CRS, Extent, and Crop)") # Apply a mask to the first raster mask <- terra::rast(nrows = 10, ncols = 10, vals = sample(c(0, 1), 100, replace = TRUE)) masked_r1 <- hb_modify_raster(r1, mask = mask) plot(masked_r1, main = "Masked Raster") ## End(Not run)## Not run: # Create sample raster datasets or load: "r1" and "r2" # Modify the CRS and extent of the first raster modified_r1 <- hb_modify_raster(r1, crs = "EPSG:4326", extent = c(0, 1000, 0, 1000)) plot(modified_r1, main = "Modified Raster (CRS and Extent)") # Modify the CRS, extent, and crop the second raster modified_r2 <- hb_modify_raster(r2, crs = "EPSG:4326", extent = c(0, 1000, 0, 1000), crop_extent = modified_r1) plot(modified_r2, main = "Modified Raster (CRS, Extent, and Crop)") # Apply a mask to the first raster mask <- terra::rast(nrows = 10, ncols = 10, vals = sample(c(0, 1), 100, replace = TRUE)) masked_r1 <- hb_modify_raster(r1, mask = mask) plot(masked_r1, main = "Masked Raster") ## End(Not run)
Modifies the CRS, applies cropping, masking, and extent adjustments to a shapefile based on specified parameters or derived from another shapefile.
hb_modify_shp(shapefile, crs = NULL, extent = NULL, crop = NULL, mask = NULL)hb_modify_shp(shapefile, crs = NULL, extent = NULL, crop = NULL, mask = NULL)
shapefile |
An sf object to be modified. This represents the shapefile dataset that will undergo modifications. |
crs |
Optional. A character string specifying the new Coordinate Reference System (CRS) (e.g., "EPSG:4326") or an sf object to derive the CRS from. If provided, the shapefile will be reprojected to this CRS. |
extent |
Optional. An sf object specifying the new extent. If provided, the shapefile will be modified to match this extent. |
crop |
Optional. An sf object specifying the extent to crop to. If provided, the shapefile will be cropped to this extent. |
mask |
Optional. An sf object to be used as a mask. If provided, the shapefile will be masked by this shapefile. |
Designed to provide a comprehensive set of modifications to a shapefile dataset. This includes changing the CRS, adjusting the extent, cropping, and masking using other shapefiles.
A modified sf object with the specified modifications applied.
## Not run: # Create two example sf polygons (or load it) library(sf) poly1 <- st_as_sf(data.frame( id = 1, geom = st_sfc(st_polygon(list(rbind( c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0) )))) )) poly2 <- st_as_sf(data.frame( id = 2, geom = st_sfc(st_polygon(list(rbind( c(0.5, 0.5), c(1.5, 0.5), c(1.5, 1.5), c(0.5, 1.5), c(0.5, 0.5) )))) )) # Modify the CRS using another object's CRS modified_shapefile <- hb_modify_shp(poly1, crs = poly2) plot(modified_shapefile, main = "Modified Shapefile (CRS)") # Modify the extent using another object's extent modified_shapefile <- hb_modify_shp(poly1, extent = poly2) plot(modified_shapefile, main = "Modified Shapefile (Extent)") # Crop the shapefile using another modified_shapefile <- hb_modify_shp(poly1, crop = poly2) plot(modified_shapefile, main = "Cropped Shapefile") # Apply a mask using another shapefile modified_shapefile <- hb_modify_shp(poly1, mask = poly2) plot(modified_shapefile, main = "Masked Shapefile") ## End(Not run)## Not run: # Create two example sf polygons (or load it) library(sf) poly1 <- st_as_sf(data.frame( id = 1, geom = st_sfc(st_polygon(list(rbind( c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0) )))) )) poly2 <- st_as_sf(data.frame( id = 2, geom = st_sfc(st_polygon(list(rbind( c(0.5, 0.5), c(1.5, 0.5), c(1.5, 1.5), c(0.5, 1.5), c(0.5, 0.5) )))) )) # Modify the CRS using another object's CRS modified_shapefile <- hb_modify_shp(poly1, crs = poly2) plot(modified_shapefile, main = "Modified Shapefile (CRS)") # Modify the extent using another object's extent modified_shapefile <- hb_modify_shp(poly1, extent = poly2) plot(modified_shapefile, main = "Modified Shapefile (Extent)") # Crop the shapefile using another modified_shapefile <- hb_modify_shp(poly1, crop = poly2) plot(modified_shapefile, main = "Cropped Shapefile") # Apply a mask using another shapefile modified_shapefile <- hb_modify_shp(poly1, mask = poly2) plot(modified_shapefile, main = "Masked Shapefile") ## End(Not run)
Converts a series of raster files or loaded raster objects into a multidimensional dataset for time analysis. This is the first step in a sequence of functions to analyze habitat trends.
hb_multiD_raster(raster_files, time_points)hb_multiD_raster(raster_files, time_points)
raster_files |
A character vector of file paths to raster files or a list of |
time_points |
A numeric vector of time points corresponding to the raster files (e.g., 2022, 2023). |
A SpatRaster object representing the multidimensional dataset.
## Not run: # Create sample rasters or load it: "r1" and "r2" raster_files <- list(r1, r2) time_points <- c(2022, 2023) # Create multidimensional raster layer multidimensional_raster <- hb_multiD_raster(raster_files, time_points) # Aggregate to compute the mean aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) # Analyze changes trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) # Plot the time series data hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)## Not run: # Create sample rasters or load it: "r1" and "r2" raster_files <- list(r1, r2) time_points <- c(2022, 2023) # Create multidimensional raster layer multidimensional_raster <- hb_multiD_raster(raster_files, time_points) # Aggregate to compute the mean aggregated_raster <- hb_agg_md_raster(multidimensional_raster, fun = mean) # Analyze changes trends <- hb_analyze_changes(multidimensional_raster, fun = trend_analysis) # Plot the time series data hb_plot_timesrs(trends, output_path = tempfile(fileext = ".tif")) ## End(Not run)
Calculates various optimal thresholds based on different criteria such as max(sp + se), max(kappa), and others.
hb_opt_th(eval_metrics)hb_opt_th(eval_metrics)
eval_metrics |
A data frame with evaluation metrics. |
A list with optimal thresholds for different criteria.
## Not run: # Assuming the user has already extracted evaluation metrics example_function(metrics) # Calculate optimal thresholds thresholds <- hb_opt_th(eval_metrics) print(thresholds) # Example usage of the extracted threshold with existing functions: max_sp_se_threshold <- thresholds$max_sp_se binary_map <- hb_binary(r, th = max_sp_se_threshold) habitat_analysis <- hb_an_habitat(x1, x2, threshold = max_sp_se_threshold) range_analysis <- hb_range(x, y, th = max_sp_se_threshold) ## End(Not run)## Not run: # Assuming the user has already extracted evaluation metrics example_function(metrics) # Calculate optimal thresholds thresholds <- hb_opt_th(eval_metrics) print(thresholds) # Example usage of the extracted threshold with existing functions: max_sp_se_threshold <- thresholds$max_sp_se binary_map <- hb_binary(r, th = max_sp_se_threshold) habitat_analysis <- hb_an_habitat(x1, x2, threshold = max_sp_se_threshold) range_analysis <- hb_range(x, y, th = max_sp_se_threshold) ## End(Not run)
Plots a habitat map with enhanced visualization options using ggplot2.
hb_plot( raster, main = "Habitat Map", lonlat = TRUE, add_north_arrow = FALSE, background_color = "white", habitat_palette = "viridis", add_legend = TRUE )hb_plot( raster, main = "Habitat Map", lonlat = TRUE, add_north_arrow = FALSE, background_color = "white", habitat_palette = "viridis", add_legend = TRUE )
raster |
A SpatRaster object representing the habitat map. |
main |
Title for the plot. |
lonlat |
Logical. If TRUE, plots the habitat map on a longitude and latitude scale. |
add_north_arrow |
Logical. If TRUE, adds a North arrow to the plot. |
background_color |
Character string specifying the background color of the map. Default is "white". |
habitat_palette |
Character string specifying the palette for habitat areas. |
add_legend |
Logical. If TRUE, includes a legend in the plot. |
This function plots a habitat map with various optional parameters for enhanced visualization.
## Not run: # Create a sample raster or load it! # Plot habitat map hb_plot( raster, main = "Sample Habitat Map", lonlat = TRUE, add_north_arrow = TRUE, background_color = "lightblue", add_legend = TRUE, habitat_palette = "viridis" ) ## End(Not run)## Not run: # Create a sample raster or load it! # Plot habitat map hb_plot( raster, main = "Sample Habitat Map", lonlat = TRUE, add_north_arrow = TRUE, background_color = "lightblue", add_legend = TRUE, habitat_palette = "viridis" ) ## End(Not run)
Plots a SpatRaster highlighting areas of habitat gain, loss, stability, and absence using terra's native plotting.
hb_plot_changes( changes_raster, title = "Changes", xlab = "Longitude", ylab = "Latitude", bg_color = "white" )hb_plot_changes( changes_raster, title = "Changes", xlab = "Longitude", ylab = "Latitude", bg_color = "white" )
changes_raster |
A SpatRaster object generated by |
title |
Optional. Title of the plot. Default is "Changes". |
xlab |
Optional. Label for the x-axis. Default is "Longitude". |
ylab |
Optional. Label for the y-axis. Default is "Latitude". |
bg_color |
Optional. Background color of the plot region and NA cells. Default is "white". |
Uses terra::plot() for fast, seam-free visualization of rasters.
## Not run: changes_raster <- hb_changes(r1, r2) # Plot habitat changes hb_plot_changes(changes_raster, title = "Habitat Changes") ## End(Not run)## Not run: changes_raster <- hb_changes(r1, r2) # Plot habitat changes hb_plot_changes(changes_raster, title = "Habitat Changes") ## End(Not run)
Visualizes the trends in habitat suitability. This is the final step in a sequence of functions to analyze and visualize habitat trends.
hb_plot_timesrs( trends, lon_min = NULL, lon_max = NULL, lat_min = NULL, lat_max = NULL, low_color = "darkred", mid_color = "gray90", high_color = "darkblue", x_label = "Longitude", y_label = "Latitude", plot_title = "Habitat Suitability Trends", bg_color = "white", output_path = NULL )hb_plot_timesrs( trends, lon_min = NULL, lon_max = NULL, lat_min = NULL, lat_max = NULL, low_color = "darkred", mid_color = "gray90", high_color = "darkblue", x_label = "Longitude", y_label = "Latitude", plot_title = "Habitat Suitability Trends", bg_color = "white", output_path = NULL )
trends |
A |
lon_min |
Minimum longitude for plotting the map. |
lon_max |
Maximum longitude for plotting the map. |
lat_min |
Minimum latitude for plotting the map. |
lat_max |
Maximum latitude for plotting the map. |
low_color |
Color for the low end of the gradient. |
mid_color |
Color for the midpoint of the gradient. |
high_color |
Color for the high end of the gradient. |
x_label |
Custom x-axis label. |
y_label |
Custom y-axis label. |
plot_title |
Custom plot title. |
bg_color |
Background color for the plot. |
output_path |
A character string representing the file path to save the plot. If |
A ggplot object representing the time series plot.
## Not run: # Create dummy trends data for plotting trends <- list(data = matrix(runif(100), ncol = 10)) hb_plot_timesrs(trends, lon_min = -10, lon_max = 10, lat_min = 35, lat_max = 45, low_color = "blue", mid_color = "white", high_color = "red", x_label = "Longitude", y_label = "Latitude", plot_title = "My Custom Title", bg_color = "black", output_path = tempfile(fileext = ".tif") ) ## End(Not run)## Not run: # Create dummy trends data for plotting trends <- list(data = matrix(runif(100), ncol = 10)) hb_plot_timesrs(trends, lon_min = -10, lon_max = 10, lat_min = 35, lat_max = 45, low_color = "blue", mid_color = "white", high_color = "red", x_label = "Longitude", y_label = "Latitude", plot_title = "My Custom Title", bg_color = "black", output_path = tempfile(fileext = ".tif") ) ## End(Not run)
Computes metrics such as gain, loss, stable areas, and total changes between two binary raster maps. Provides a detailed analysis of habitat changes over time.
hb_range(x, y, th)hb_range(x, y, th)
x |
A SpatRaster object representing the current habitat (binary). This raster should contain binary values indicating habitat presence and absence. |
y |
A SpatRaster object representing the future habitat (binary). This raster should also contain binary values indicating habitat presence and absence. |
th |
A numeric threshold value between 0 and 1, used to convert continuous data into a binary format before analysis. |
Designed to compare two binary raster maps representing habitat data at different time points. Calculates various metrics to summarize the changes between the two maps, which can be used to assess the impact of environmental changes or conservation efforts.
A list containing:
Compt.By.Models: A data frame with detailed metrics, including loss, gain, stable areas, and percentage changes.
Diff.By.Pixel: A SpatRaster showing pixel-wise differences between the current and future habitat maps.
## Not run: # Create sample binary raster datasets or load it: for instance "r1" and "r2" # Analyze habitat changes result <- hb_range(r1, r2, th = 0.5) # Display the computed metrics print(result$Compt.By.Models) # Plot the habitat changes hb_plot(result$Compt.By.Models) ## End(Not run)## Not run: # Create sample binary raster datasets or load it: for instance "r1" and "r2" # Analyze habitat changes result <- hb_range(r1, r2, th = 0.5) # Display the computed metrics print(result$Compt.By.Models) # Plot the habitat changes hb_plot(result$Compt.By.Models) ## End(Not run)
Plots habitat changes as a bar chart. The bar chart visualizes the percentage of loss, gain, and overall species range change.
hb_range_plot(data)hb_range_plot(data)
data |
A data frame containing the habitat change metrics. This data frame should include the percentage metrics such as |
Designed to take the habitat change metrics computed by the hb_habitat_range function and visualize them in a bar chart. This helps in understanding the extent of habitat changes visually.
None. This function is used for its side effect of creating and displaying the plot.
## Not run: # Assume result is obtained from hb_habitat_range function # result <- hb_habitat_range(r1, r2, th = 0.5) # Plot the habitat changes hb_range_plot(result) ## End(Not run)## Not run: # Assume result is obtained from hb_habitat_range function # result <- hb_habitat_range(r1, r2, th = 0.5) # Plot the habitat changes hb_range_plot(result) ## End(Not run)
Converts a binary or continuous SpatRaster object to a polygon.
hb_ras_to_pol(raster, binary = FALSE)hb_ras_to_pol(raster, binary = FALSE)
raster |
A SpatRaster object to be converted. |
binary |
Logical. If |
The function is designed to convert a raster dataset into a polygon, which is useful for visualizing raster data as vector data and performing vector-based spatial analyses.
An sf object representing the raster converted to polygons.
## Not run: # Create a sample binary raster or load it: "binary_raster" # Convert the binary raster to polygons binary_polygons <- hb_raster_to_polygon(binary_raster, binary = TRUE) plot(binary_polygons) # Create a sample raster or load it: "raster1" # Convert the raster to polygons continuous_polygons <- hb_ras_to_pol(raster1) plot(continuous_polygons) ## End(Not run)## Not run: # Create a sample binary raster or load it: "binary_raster" # Convert the binary raster to polygons binary_polygons <- hb_raster_to_polygon(binary_raster, binary = TRUE) plot(binary_polygons) # Create a sample raster or load it: "raster1" # Convert the raster to polygons continuous_polygons <- hb_ras_to_pol(raster1) plot(continuous_polygons) ## End(Not run)
Reclassifies raster values based on specified bins. The raster values are grouped into specified bins, and each bin is assigned a new value according to the provided values vector.
hb_reclass(raster, bins, values)hb_reclass(raster, bins, values)
raster |
A SpatRaster object to be reclassified. Represents the raster dataset whose values are to be reclassified. |
bins |
A numeric vector defining the breakpoints for reclassification. These breakpoints specify the intervals for reclassification. |
values |
A numeric vector defining the new values for each bin. Each element in this vector corresponds to a bin defined by the |
Designed to take a continuous or categorical raster dataset and reclassify its values based on specified breakpoints (bins). This is useful for simplifying or categorizing raster data for further analysis, visualization, or modeling.
A reclassified SpatRaster object with values reclassified according to the specified bins and new values.
## Not run: # Create a sample raster dataset or load it: "raster1" # Reclassify raster values using specified bins and new values reclassified_raster <- hb_reclass( raster1, bins = c(0, 0.25, 0.5, 0.75, 1), values = c(1, 2, 3, 4) ) # Plot the resulting reclassified raster plot(reclassified_raster, main = "Reclassified Raster Values") ## End(Not run)## Not run: # Create a sample raster dataset or load it: "raster1" # Reclassify raster values using specified bins and new values reclassified_raster <- hb_reclass( raster1, bins = c(0, 0.25, 0.5, 0.75, 1), values = c(1, 2, 3, 4) ) # Plot the resulting reclassified raster plot(reclassified_raster, main = "Reclassified Raster Values") ## End(Not run)
Checks whether two raster datasets have identical extent, CRS (Coordinate Reference System), dimensions, and resolution, ensuring compatibility for further analysis.
hb_res_check(x, y)hb_res_check(x, y)
x |
A RasterLayer or SpatRaster object representing the first dataset. This is the initial raster that will be compared. |
y |
A RasterLayer or SpatRaster object representing the second dataset. This is the raster that will be compared against the first raster. |
Designed to validate the compatibility of two raster datasets by checking their extent, CRS, dimensions, and resolution. This is crucial for ensuring that subsequent spatial analyses can be performed accurately without encountering alignment issues.
Returns TRUE if all checks pass, otherwise throws an error indicating which check failed.
## Not run: # Create sample raster datasets or load it: "r1" and "r2" # Validate that the raster datasets have identical properties hb_res_check(r1, r2) # Returns TRUE if all checks pass ## End(Not run)## Not run: # Create sample raster datasets or load it: "r1" and "r2" # Validate that the raster datasets have identical properties hb_res_check(r1, r2) # Returns TRUE if all checks pass ## End(Not run)
Provides summary statistics for a given SpatRaster object, calculating key statistical measures to summarize the distribution of values within the raster dataset.
hb_sstat(raster)hb_sstat(raster)
raster |
A SpatRaster object representing the raster dataset for which summary statistics will be generated. |
Designed to take a raster dataset and compute summary statistics that provide insights into the data's distribution and variability. These statistics are useful for understanding the overall characteristics of the raster data.
A list containing summary statistics of the raster values, including the mean, median, standard deviation, minimum, and maximum of the raster values.
## Not run: # Create a sample raster dataset or load it: "raster1" # Generate the summary statistics for the raster raster_summary <- hb_sstat(raster1) # Display the summary statistics print(raster_summary) ## End(Not run)## Not run: # Create a sample raster dataset or load it: "raster1" # Generate the summary statistics for the raster raster_summary <- hb_sstat(raster1) # Display the summary statistics print(raster_summary) ## End(Not run)
Stacks multiple data frames into a single data frame.
hb_stack_dfs(dfs)hb_stack_dfs(dfs)
dfs |
A list of data frames to be stacked. |
This function takes a list of data frames and stacks them into a single data frame by row binding. It is useful for combining multiple data frames for further analysis.
A single data frame that combines all input data frames by row binding.
## Not run: # Create sample data frames or load it: "df1" and "df2" # Stack the data frames stacked_df <- hb_stack_dfs(list(df1, df2)) print(stacked_df) ## End(Not run)## Not run: # Create sample data frames or load it: "df1" and "df2" # Stack the data frames stacked_df <- hb_stack_dfs(list(df1, df2)) print(stacked_df) ## End(Not run)
Stacks multiple SpatRaster objects into a single SpatRaster object.
hb_stack_rasters(rasters)hb_stack_rasters(rasters)
rasters |
A list of SpatRaster objects to be stacked. |
This function takes a list of SpatRaster objects and stacks them into a single SpatRaster object. It is useful for combining multiple raster layers for further analysis.
A SpatRaster object that combines all input raster layers.
## Not run: # Create sample raster datasets or load it: "raster1" and "raster2" # Stack the rasters stacked_rasters <- hb_stack_rasters(list(raster1, raster2)) plot(stacked_rasters) ## End(Not run)## Not run: # Create sample raster datasets or load it: "raster1" and "raster2" # Stack the rasters stacked_rasters <- hb_stack_rasters(list(raster1, raster2)) plot(stacked_rasters) ## End(Not run)
Converts a RasterLayer object to a SpatRaster object.
raster_to_spat(raster_layer)raster_to_spat(raster_layer)
raster_layer |
A RasterLayer object. |
A SpatRaster object.
Converts a SpatRaster object to a RasterLayer object.
spat_to_raster(spat_raster)spat_to_raster(spat_raster)
spat_raster |
A SpatRaster object. |
A RasterLayer object.