R/lets_subsetPAMenv.R

Defines functions lets.subsetPAMenv

Documented in lets.subsetPAMenv

#' Subset an environmental PAM by species names
#'
#' Subsets an environmental-space presence-absence matrix (PAM) generated by
#' \code{\link{lets.envpam}} by retaining only a selected set of species.
#' Species not included in \code{species} are removed from both tabular
#' components of the object, and species richness is recalculated and written
#' back to the corresponding raster layers.
#'
#' Optionally, cells with zero richness after subsetting can be removed from the
#' tabular components.
#'
#' @param x An environmental PAM produced by \code{\link{lets.envpam}}.
#' @param species A character vector with species names to retain in the PAM.
#' @param remove.cells Logical. If \code{TRUE}, rows with zero richness after
#'   subsetting are removed from matrices. Default is
#'   \code{TRUE}.
#'
#' @return A list with the same structure as the input object:
#' \itemize{
#'   \item \code{x[[1]]}: the subsetted env PAM table.
#'   \item \code{x[[2]]}: the subsetted geo PAM table.
#'   \item \code{x[[3]]}: the raster associated with env PAM, updated with
#'   recalculated richness values.
#'   \item \code{x[[4]]}: the raster associated with geo PAM, updated with
#'   recalculated richness values.
#' }
#'
#' @details
#' If none of the supplied species names match the species present in the PAM,
#' the function stops with an error before modifying the object.
#'
#' @examples
#' \dontrun{
#' data("Phyllomedusa")
#' data("prec")
#' data("temp")
#'
#' prec <- unwrap(prec)
#' temp <- unwrap(temp)
#'
#' PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE)
#' envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE)
#' colnames(envs) <- c("Temperature", "Precipitation")
#' wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR"))
#' PAM <- lets.pamcrop(PAM, vect(wrld_simpl))
#'
#' res <- lets.envpam(PAM, envs)
#'
#' lets.plot.envpam(
#'   x = res,
#'   species = NULL,
#'   cell_id_env = NULL,
#'   cell_id_geo = NULL,
#'   plot.grid = TRUE,
#'   world = TRUE,
#'   mar = c(4, 4, 4, 4)
#' )
#'
#' sub <- sample(PAM$Species_name, 10)
#' pam_sub <- lets.subsetPAMenv(res, sub)
#' lets.plot.envpam(pam_sub)
#' }
#'
#' @seealso \code{\link{lets.envpam}}, \code{\link{lets.plot.envpam}},
#'   \code{\link{lets.presab}}, \code{\link{lets.addvar}}
#'
#' @export


lets.subsetPAMenv <- function(x, species, remove.cells = TRUE) {
  # Get column names from the first PAM table.
  # The first three columns are assumed to contain metadata, whereas the
  # remaining columns correspond to species.
  sps_env <- colnames(x[[1]])
  
  # Identify which species columns should be kept.
  keep_env <- sps_env %in% species
  
  # Always preserve the first three metadata columns.
  keep_env[1:3] <- TRUE
  
  # If only the metadata columns remain, then no species were matched.
  if (sum(keep_env) == 3) {
    stop(
      paste0(
        "No species matched between input data and reference dataset ",
        "after subsetting. Verify species naming and data alignment."
      )
    )
  }
  
  # Subset the first PAM table to metadata columns plus matched species.
  x[[1]] <- x[[1]][, keep_env, drop = FALSE]
  
  # Recalculate richness for each row in the first PAM component.
  rich_env <- as.numeric(rowSums(x[[1]][, -(1:3), drop = FALSE]))
  
  # Convert the coordinates stored in columns 2 and 3 into raster cell indices
  # for the raster associated with the first PAM table.
  cells <- terra::cellFromXY(x[[3]], x[[1]][, 2:3, drop = FALSE])
  
  # Update raster values with the recalculated richness values.
  terra::values(x[[3]])[cells] <- rich_env
  
  
  # Get column names from the second PAM table.
  # The first four columns are assumed to contain metadata, whereas the
  # remaining columns correspond to species.
  sps_geo <- colnames(x[[2]])
  
  # Identify which species columns should be kept.
  keep_geo <- sps_geo %in% species
  
  # Always preserve the first four metadata columns.
  keep_geo[1:4] <- TRUE
  
  # Subset the second PAM table to metadata columns plus matched species.
  x[[2]] <- x[[2]][, keep_geo, drop = FALSE]
  
  # Recalculate richness for each row in the second PAM component.
  rich_geo <- as.numeric(rowSums(x[[2]][, -(1:4), drop = FALSE]))
  
  # Rasterize the coordinates stored in columns 3 and 4 of the second table
  # and write the recalculated richness values to the associated raster.
  x[[4]] <- terra::rasterize(
    x[[2]][, c(3:4), drop = FALSE],
    x[[4]],
    rich_geo
  )
  
  # Optionally remove rows with zero richness from both tabular components.
  # This affects only the tables, not the spatial extent or resolution of
  # the associated rasters.
  if (remove.cells) {
    x[[1]] <- x[[1]][rich_env > 0, , drop = FALSE]
    x[[2]] <- x[[2]][rich_geo > 0, , drop = FALSE]
  }
  
  return(x)
}

Try the letsR package in your browser

Any scripts or data that you put into this service are public.

letsR documentation built on Nov. 26, 2026, 9:09 a.m.