R/lets_summaryze_cells.R

Defines functions lets.summaryze.cells

Documented in lets.summaryze.cells

#' Summarize per-cell descriptors to species-level values
#'
#' @title Aggregate cell-wise metrics across occupied cells per species
#'
#' @description
#' Given a presence–absence matrix in either attribute space (from
#' \code{\link{lets.attrpam}}) or environmental space (from
#' \code{\link{lets.envpam}}) and a table of per-cell descriptors
#' (from \code{\link{lets.attrcells}} or \code{\link{lets.envcells}}),
#' this function aggregates each descriptor across the set of cells
#' occupied by each species, using a user-supplied summary function
#' (e.g., \code{mean}, \code{median}, \code{sum}).
#'
#' @param x A list returned by \code{\link{lets.attrpam}} (attribute space) or
#'   \code{\link{lets.envpam}} (environmental space). The first element
#'   \code{x[[1]]} must be a matrix/data.frame whose first three columns are the
#'   cell identifier and the two coordinate/axis columns; species presence–absence
#'   columns start at column 4.
#' @param y A \code{data.frame} of per-cell descriptors with the same row order as
#'   \code{x[[1]]}. The first column must be the cell identifier
#'   (e.g., \code{Cell_attr} or \code{Cell_env}); descriptor columns start at column 2.
#' @param func A summary function to aggregate a descriptor across the cells
#'   occupied by a species (default \code{mean}). The function must return a single
#'   numeric value and should handle \code{na.rm} internally if needed (note that
#'   this routine already removes \code{NA}s per species via \code{na.omit}).
#'
#' @return
#' A \code{data.frame} with one row per species and one column per descriptor,
#' containing the aggregated (e.g., mean) value of each descriptor across all
#' cells where that species is present. The first column, \code{Species}, holds
#' the species names copied from \code{colnames(x[[1]])[4:ncol(x[[1]])]}.
#'
#' @details
#' Internally, for each species column in \code{x[[1]]} (starting at column 4),
#' the function builds a logical mask of occupied cells (> 0). It then subsets
#' the descriptor table \code{y} to those rows and applies \code{func} column-wise
#' to \code{y[occupied, -1]} (dropping the ID column). Missing values are removed
#' with \code{stats::na.omit} prior to aggregation.
#'
#' @seealso
#' \code{\link{lets.attrpam}}, \code{\link{lets.envpam}},
#' \code{\link{lets.attrcells}}, \code{\link{lets.envcells}}
#'
#' @examples
#' \dontrun{
#' ## --------------------------
#' ## ATTRIBUTE SPACE WORKFLOW
#' ## --------------------------
#' set.seed(1)
#' n <- 2000
#' Species <- paste0("sp", 1:n)
#' trait_a <- rnorm(n)
#' trait_b <- trait_a * 0.2 + rnorm(n)
#' df <- data.frame(Species, trait_a, trait_b)
#'
#' # Build AttrPAM and compute per-cell descriptors
#' x_attr <- lets.attrpam(df, n_bins = 30)
#' y_attr <- lets.attrcells(x_attr)
#'
#' # Summarize descriptors per species (e.g., mean across occupied cells)
#' head(lets.summaryze.cells(x_attr, y_attr, func = mean))
#'
#' ## ------------------------------
#' ## ENVIRONMENTAL SPACE WORKFLOW
#' ## ------------------------------
#' 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, terra::vect(wrld_simpl))
#'
#' res_env <- lets.envpam(PAM, envs, n_bins = 30)
#' y_env   <- lets.envcells(res_env, perc = 0.2)
#'
#' # Summarize environmental-space descriptors per species
#' head(lets.summaryze.cells(res_env, y_env, func = mean))
#' }
#'
#' @export 
#' 
lets.summaryze.cells <- function(x, y, func = mean) {
  # x[[1]] is expected to be the cell-by-species matrix:
  #  - columns 1:3 = [cell_id, axis1, axis2]
  #  - columns 4:n = species presence/absence (0/1)
  pam_x <- x[[1]]
  
  id_x <- pam_x[, 1]
  id_y <- y[, 1]
  
  y <- y[match(id_x, id_y), , drop = FALSE]
  
  if (any(y[, 1] != pam_x[, 1])) {
    stop("IDs in y do not match IDs in x after ordering.")
  }
  
  # Total number of columns in PAM (cells + coords + species)
  n <- ncol(pam_x)
  
  # Species columns start at index 4 (as per package convention)
  seq <- 4:n
  
  # Preallocate the output matrix:
  #   rows   = number of species
  #   cols   = number of descriptors in 'y' minus the ID column
  sum_cells <- matrix(
    nrow = n - 3, ncol = ncol(y) - 1,
    dimnames = list(NULL, colnames(y)[-1])
  )
  
  # For each species, aggregate each descriptor across occupied cells
  for (i in seq) {
    # Logical mask of cells where species i is present
    cells <- pam_x[, i] > 0
    
    # Apply the summary function column-wise on descriptors (drop ID col),
    # removing NAs for that species (stats::na.omit)
    sum_cells[i - 3, ] <- apply(
      na.omit(y[cells, -1, drop = FALSE]),
      2, func
    )
  }
  
  # Assemble the final data frame: species names + summarized descriptors
  result <- data.frame(
    "Species" = colnames(pam_x)[seq],
    sum_cells
  )
  
  # Ensure descriptor column names match input 'y'
  colnames(result)[-1] <- colnames(y)[-1]
  
  return(result)
}

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.