R/asc_entities.R

Defines functions .entity_indices asc_entities

Documented in asc_entities

#' Identify Functional Entities (Species Clustering)
#'
#' @description
#' Groups species with similar traits into functional entities by hierarchical
#' clustering (Gower distance and Ward's method by default). If neither
#' \code{k} nor \code{h} is given, the number of entities is chosen as the one
#' with the highest mean silhouette width. The result can be passed to
#' \code{\link{asc_null}} (A on counts summed by entity) and
#' \code{\link{asc_transitions}} (displacement between vs within entities)
#' to explore whether species were replaced by functionally similar ones.
#' This use is exploratory: only replacement within an entity is seen
#' (similar species placed in different entities look like a change between
#' entities, so a negative result does not rule out redundancy), the signal
#' was weak in the validation except for strong compensation, and it depends
#' on the number of entities.
#'
#' @details
#' Three criteria are computed for \code{k = 2, ..., k_max} on the same tree:
#' \itemize{
#'   \item \strong{Mean silhouette width} (Rousseeuw 1987), on the trait
#'     distance. Used to choose \code{k} by default. Below 0.25: no clear
#'     groups; 0.25-0.5: weak structure.
#'   \item \strong{Mojena's rule}: first fusion height above the mean plus 1.25
#'     standard deviations of all fusion heights.
#'   \item \strong{Gap statistic} (Tibshirani et al. 2001), on the PCoA
#'     coordinates, with the \code{"Tibs2001SEmax"} rule. \code{k = 1} means no
#'     natural groups: the entities then discretise a continuum, which is still
#'     useful, but conclusions should be checked with neighbouring values of
#'     \code{k}.
#' }
#' In the validation (continuous traits of 42 butterfly species), very coarse
#' entities (k = 5, Mojena's choice there) classified part of a directed change
#' as "within entities", whereas the silhouette choice (k = 13) did not. Even
#' with k = 13, compensation between similar species was detected only when it
#' was strong, and not when the species fell in different entities. With discrete traits,
#' \code{h = 0} gives entities in the strict sense (species sharing exactly the
#' same trait combination); this use has not been evaluated by simulation.
#'
#' @param traits A data frame or matrix of functional traits (row names =
#'   species).
#' @param dist_method Character. Distance metric. Default is \code{"gower"}.
#' @param hclust_method Character. Agglomeration method. Default is \code{"ward.D2"}.
#' @param k Integer. Number of entities. If \code{NULL} (and \code{h} is
#'   \code{NULL}), chosen by the silhouette.
#' @param h Numeric. Height at which to cut the dendrogram (alternative to \code{k}).
#' @param k_max Integer. Largest \code{k} evaluated by the criteria. Default 15.
#' @param B Integer. Number of reference data sets for the gap statistic. Default 100.
#' @param seed Integer or \code{NULL}. Seed for the gap statistic (the user's
#'   random stream is left unchanged).
#' @param correction,type,weights Passed to the trait distance; see
#'   \code{\link{asc_paired}}.
#'
#' @return An S3 object of class \code{ascent_entities} (it also carries the
#'   class \code{ascfcd_entities} of ascent 0.5.0, which will be dropped in
#'   0.6.0) with
#'   \code{membership} (named vector: species -> entity, accepted by
#'   \code{asc_null()} and \code{asc_transitions()}), \code{k},
#'   \code{entity_classification} (species, entity and traits),
#'   \code{indices} (silhouette and gap by \code{k}), \code{suggestions}
#'   (\code{k} by silhouette, Mojena and gap), \code{silhouette_max},
#'   \code{n_species_per_entity}, \code{distance_matrix}, \code{hclust_obj},
#'   \code{method} and \code{metric}.
#'
#' @references
#' Rousseeuw, P. J. (1987). Silhouettes: a graphical aid to the interpretation
#' and validation of cluster analysis. Journal of Computational and Applied
#' Mathematics, 20, 53-65.
#'
#' Tibshirani, R., Walther, G. & Hastie, T. (2001). Estimating the number of
#' clusters in a data set via the gap statistic. Journal of the Royal
#' Statistical Society B, 63, 411-423.
#'
#' Mojena, R. (1977). Hierarchical grouping methods and stopping rules: an
#' evaluation. The Computer Journal, 20, 359-363.
#'
#' @examples
#' \donttest{
#' # Group the 24 species of birds_sim by their traits
#' ent <- asc_entities(birds_sim$traits, k_max = 10, B = 50, seed = 1)
#'
#' # Suggested number of entities (silhouette, Mojena, gap) and their sizes
#' summary(ent)
#'
#' # Is the change at "Logged" a reorganisation of the functional groups
#' # (shift between entities) or a replacement among similar species (within)?
#' res <- asc_paired(birds_sim$traits, birds_sim$counts,
#'                   sites = birds_sim$samples$site,
#'                   time = birds_sim$samples$time, ref_time = "Before")
#' asc_transitions(res, entities = ent)$Logged$entities
#' }
#'
#' @export
asc_entities <- function(traits, dist_method = "gower", hclust_method = "ward.D2",
                         k = NULL, h = NULL, k_max = 15, B = 100, seed = NULL,
                         correction = c("none", "sqrt"), type = NULL, weights = NULL) {
  correction <- match.arg(correction)
  if (is.null(rownames(traits))) stop("'traits' needs row names (species).")
  n <- nrow(traits)
  if (n < 4) stop("At least 4 species are needed to form entities.")

  d_mat <- .trait_distance(traits, dist_method, correction, type, weights)
  hc <- stats::hclust(d_mat, method = hclust_method)

  F_mat <- .build_functional_space(traits, dist_method, "variance", 0.80,
                                   correction, type, weights)$F_mat
  idx <- if (!is.null(seed)) withr::with_seed(seed, .entity_indices(hc, d_mat, F_mat, k_max, B, hclust_method))
         else .entity_indices(hc, d_mat, F_mat, k_max, B, hclust_method)

  if (is.null(k) && is.null(h)) k <- idx$k_silhouette
  if (idx$silhouette_max < 0.25) {
    warning(sprintf("Maximum mean silhouette %.2f: no clear groups of species.", idx$silhouette_max))
  } else if (idx$silhouette_max < 0.5) {
    message(sprintf("Maximum mean silhouette %.2f: weak group structure.", idx$silhouette_max))
  }
  if (idx$k_gap == 1) {
    message("Gap statistic finds no natural groups (k = 1): entities discretise a continuum; ",
            "check conclusions with neighbouring values of k.")
  }

  clusters <- stats::cutree(hc, k = k, h = h)
  membership <- stats::setNames(paste0("Entity_", clusters), rownames(traits))
  res_df <- cbind(data.frame(Species = rownames(traits), Entity_ID = unname(membership),
                             stringsAsFactors = FALSE), traits)
  rownames(res_df) <- NULL

  output <- list(
    membership = membership,
    k = length(unique(clusters)),
    entity_classification = res_df,
    indices = idx$table,
    suggestions = c(silhouette = idx$k_silhouette, mojena = idx$k_mojena, gap = idx$k_gap),
    silhouette_max = idx$silhouette_max,
    n_species_per_entity = table(membership),
    distance_matrix = d_mat,
    hclust_obj = hc,
    method = hclust_method,
    metric = dist_method,
    correction = correction
  )
  class(output) <- c("ascent_entities", "ascfcd_entities")
  output
}

# Silhouette, Mojena's rule and gap statistic on the same tree (internal)
.entity_indices <- function(hc, d_mat, F_mat, k_max, B, hclust_method, c_mojena = 1.25) {
  n <- length(hc$order)
  ks <- 2:min(k_max, n - 1)
  sil <- vapply(ks, function(k)
    mean(cluster::silhouette(stats::cutree(hc, k), d_mat)[, "sil_width"]), numeric(1))
  h <- hc$height
  j <- which(h > mean(h) + c_mojena * stats::sd(h))
  k_mojena <- if (length(j)) n - min(j) + 1 else 1
  fun_clust <- function(x, k) list(cluster = stats::cutree(stats::hclust(stats::dist(x), hclust_method), k))
  gp <- cluster::clusGap(F_mat, FUNcluster = fun_clust, K.max = max(ks), B = B, verbose = FALSE)
  k_gap <- cluster::maxSE(gp$Tab[, "gap"], gp$Tab[, "SE.sim"], method = "Tibs2001SEmax")
  list(table = data.frame(k = ks, Silhouette = sil, Gap = gp$Tab[ks, "gap"],
                          Gap_SE = gp$Tab[ks, "SE.sim"]),
       k_silhouette = ks[which.max(sil)], silhouette_max = max(sil),
       k_mojena = k_mojena, k_gap = k_gap)
}

Try the ascent package in your browser

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

ascent documentation built on Nov. 30, 2026, 1:07 a.m.