R/asc_pairwise.R

Defines functions asc_pairwise

Documented in asc_pairwise

#' Functional Differences Among Many Communities
#'
#' @description
#' Measures the three layers (position, dispersion and volume) for every pair
#' of communities, e.g. sites along a gradient or the months of a series. To
#' test whether the communities differ, pass the result to
#' \code{\link{asc_null}}, which runs one global test per layer over all
#' communities (instead of one p-value per pair).
#'
#' @param traits A data frame or matrix of functional traits, one row per
#'   species (row names = species). Categorical traits should be factors.
#' @param abund A data frame or matrix of abundances, one row per community
#'   (unique row names, which name the pairs) and one column per species
#'   (matched to \code{traits} by name). Use counts of individuals for null
#'   model A.
#' @param dist_method Distance metric for the trait matrix. Default is "gower".
#' @param dim_retention Character. How many PCoA axes to keep: \code{"msd"}
#'   (default since 0.5.1: the number of axes, 2 to 10, whose Euclidean
#'   distances best reproduce the trait distances, i.e. the minimum mean
#'   squared deviation of Maire et al. 2015), \code{"variance"} (axes needed
#'   to reach \code{var_tol} of the positive variance; the default up to
#'   0.5.0, use it to reproduce earlier results) or \code{"broken_stick"}
#'   (axes explaining more than the broken-stick expectation).
#'   \code{\link{assess_functional_space}} shows the fidelity for each number
#'   of axes.
#' @param var_tol Numeric. Proportion of cumulative variance to retain when
#'   \code{dim_retention = "variance"}. Default is 0.80.
#' @param na.rm Logical. Remove missing values? Default is TRUE.
#' @param correction Character. \code{"none"} (default) builds the PCoA on the
#'   Gower dissimilarity, as in 0.1.1. \code{"sqrt"} uses its square root, which
#'   Gower (1971) showed to be Euclidean for complete data with constant
#'   weights (no negative eigenvalues). It changes the distances
#'   between species (and the shape of the space), so results with and without
#'   it are not comparable; its effect on the tests has not been evaluated by
#'   simulation. An option when the space quality is low, not a default
#'   recommendation.
#' @param type,weights Optional; passed unchanged to \code{\link[cluster]{daisy}}
#'   (e.g. to declare asymmetric binary traits or to down-weight traits coded
#'   in several columns). Default: not used.
#'
#' @note
#' **Direction of each pair:** each pair goes from \code{Community_A} to
#' \code{Community_B}, in the order of the rows of \code{abund} (the pair of
#' rows 1 and 2 is named "row1_vs_row2"). Reversing the order reverses the
#' sign of the shifts and of the leverages.
#'
#' **Normalization:** Delta FDis and Delta FRic are absolute differences (see
#' \code{\link{asc_paired}} for details).
#'
#' @return An S3 object of class \code{ascent_pairwise} (it also carries the
#'   class \code{ascfcd_pw} of ascent 0.5.0, which will be dropped in 0.6.0), a
#'   list whose main element is \code{pairwise_results} (one row per pair:
#'   \code{Community_A}, \code{Community_B}, \code{Delta_C_abs},
#'   \code{rDelta_C_pct}, \code{Delta_FDis}, \code{Delta_FRic}), with the
#'   functional space (\code{F_space}, \code{k_retained},
#'   \code{dim_retention}, \code{quality}) and the inputs needed by
#'   \code{asc_null()}.
#'
#' @examples
#' # Five communities along a gradient from primary forest to farmland
#' pw <- asc_pairwise(birds_sim$traits, birds_sim$landscape)
#'
#' # One row per pair of communities; rDelta_C_pct is the centroid shift
#' # between the two (% of the functional space)
#' summary(pw)
#'
#' # The three most different pairs
#' pr <- pw$pairwise_results
#' head(pr[order(-pr$rDelta_C_pct), c("Community_A", "Community_B", "rDelta_C_pct")], 3)
#'
#' \donttest{
#' # Do the communities differ (A), and is the variation organised by traits (B)?
#' pw <- asc_null(pw, n_perm = 99, seed = 1)
#' summary(pw)
#' }
#'
#' @export
asc_pairwise <- function(traits, abund, dist_method = "gower",
                         dim_retention = c("msd", "variance", "broken_stick"), var_tol = 0.80, na.rm = TRUE,
                         correction = c("none", "sqrt"), type = NULL, weights = NULL) {

  dim_retention <- match.arg(dim_retention)
  correction <- match.arg(correction)

  abund <- .align_species(traits, abund)
  if (is.null(rownames(abund)) || anyDuplicated(rownames(abund))) {
    stop("asc_pairwise() needs unique row names in 'abund' (they name the community pairs).")
  }
  counts <- .keep_counts(abund)
  abund_rel <- as.matrix(sweep(abund, 1, rowSums(abund, na.rm = na.rm), "/"))

  fs <- .build_functional_space(traits, dist_method, dim_retention, var_tol,
                                correction, type, weights)
  .check_fric_richness(abund, fs$k_retained)
  F_mat <- fs$F_mat

  cwm_global <- abund_rel %*% F_mat
  Dmax_regional <- max(stats::dist(F_mat))
  if(Dmax_regional == 0) Dmax_regional <- 1

  communities <- rownames(abund_rel)
  combinations <- utils::combn(communities, 2, simplify = FALSE)

  results <- data.frame()
  directional_vectors <- list(); p_ref_list <- list(); p_comp_list <- list()

  for(i in seq_along(combinations)) {
    com_A <- combinations[[i]][1]
    com_B <- combinations[[i]][2]
    pair_name <- paste(com_A, com_B, sep = "_vs_")

    p_ref_mat <- abund_rel[com_A, , drop = FALSE]
    p_comp_mat <- abund_rel[com_B, , drop = FALSE]
    p_ref_list[[pair_name]] <- p_ref_mat; p_comp_list[[pair_name]] <- p_comp_mat

    cwm_A <- cwm_global[com_A, , drop = FALSE]
    cwm_B <- cwm_global[com_B, , drop = FALSE]

    v_dir <- cwm_B - cwm_A
    directional_vectors[[pair_name]] <- v_dir
    dist_abs <- sqrt(sum(v_dir^2))
    r_delta <- (dist_abs / Dmax_regional) * 100

    topo_A <- .calc_core_topology(as.numeric(p_ref_mat), F_mat)
    topo_B <- .calc_core_topology(as.numeric(p_comp_mat), F_mat)

    res_row <- data.frame(
      Community_A = com_A, Community_B = com_B,
      Delta_C_abs = dist_abs, rDelta_C_pct = r_delta,
      Delta_FDis = topo_B$FDis - topo_A$FDis,
      Delta_FRic = topo_B$FRic - topo_A$FRic
    )
    results <- rbind(results, res_row)
  }

  output <- list(
    pairwise_results = results, Dmax_regional = Dmax_regional,
    directional_vectors = directional_vectors,
    p_ref = p_ref_list, p_comp = p_comp_list,
    cwm_global = cwm_global, F_space = F_mat, k_retained = fs$k_retained, dim_retention = dim_retention,
    var_retained = fs$var_retained, axis_var = fs$axis_var,
    quality = fs$quality,
    original_traits = traits, original_abund = abund_rel,
    counts = counts, correction = correction
  )
  class(output) <- c("ascent_pairwise", "ascfcd_pw")
  return(output)
}

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.