Package {spacc}


Title: Fast Spatial Species Accumulation Curves
Version: 1.0.0
Description: High-performance spatial species accumulation curves using fixed-focus spatially constrained rarefaction, nearest-centroid expansion, and nearest-neighbor walks with a C++ backend for speed. Supports Hill numbers (q=0,1,2), beta diversity partitioning (turnover/nestedness) at site and pooled resolution, coverage-based rarefaction and extrapolation of alpha and beta diversity, phylogenetic diversity (PD; Faith's PD, EvoHeritage, mean pairwise distance, mean nearest taxon distance), functional diversity accumulation including aggregated functional diversity and intraspecific trait variation, phylogenetic and functional redundancy, interaction network accumulation, diversity-area relationships (DAR), endemism-area curves, sampling-effort correction and fragmentation analysis, species-area relationship (SAR) models based on extreme value theory (EVT), and area-based richness extrapolation via the total-species curve. Total richness is also estimated from frequency counts, including the accumulation rate curve estimator and an estimator for sites sampled without replacement, and shift-and-rotate null models test the position of a sampling design. Multiple starting points (seeds) provide uncertainty quantification. Methods are described in Chao et al. (2014) <doi:10.1890/13-0133.1>, Baselga (2010) <doi:10.1111/j.1466-8238.2009.00490.x>, Chao and Jost (2012) <doi:10.1890/11-1952.1>, Faith (1992) <doi:10.1016/0006-3207(92)91201-3>, Ma (2018) <doi:10.1002/ece3.4425>, Borda-de-Agua et al. (2025) <doi:10.1038/s41467-025-59239-7>, Hanski et al. (2013) <doi:10.1073/pnas.1311190110>, Jost (2007) <doi:10.1890/06-1736.1>, Ugland et al. (2003) <doi:10.1046/j.1365-2656.2003.00748.x>, Chao et al. (2023) <doi:10.1002/ecm.1588>, Chiu (2023) <doi:10.1111/2041-210X.14146>, Chiu et al. (2023) <doi:10.1098/rstb.2022.0183>, Rosindell et al. (2024) <doi:10.1093/sysbio/syad072>, Wojcik et al. (2024) <doi:10.1111/2041-210X.14470>, Ridder et al. (2024) <doi:10.1111/2041-210X.14443>, Jones et al. (2025) <doi:10.1111/ddi.70080>, and Shestopaloff (2025) <doi:10.1007/s10651-025-00644-y>.
License: MIT + file LICENSE
Language: en-US
Encoding: UTF-8
Depends: R (≥ 3.5)
LinkingTo: Rcpp, RcppParallel
Imports: Rcpp, RcppParallel, stats, parallel
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown, svglite, ggplot2, cli, sf, areaOfEffect, ape, iNEXT, iNEXT.3D, iNEXT.beta3D, betapart, cluster, vegan
Config/testthat/edition: 3
VignetteBuilder: knitr
SystemRequirements: GNU make
URL: https://gillescolling.com/spacc/, https://github.com/gcol33/spacc
BugReports: https://github.com/gcol33/spacc/issues
Config/roxygen2/version: 8.1.0
NeedsCompilation: yes
Packaged: 2026-11-29 13:16:42 UTC; Gilles Colling
Author: Gilles Colling ORCID iD [aut, cre, cph]
Maintainer: Gilles Colling <gilles.colling051@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-29 13:50:02 UTC

spacc: Fast Spatial Species Accumulation Curves

Description

High-performance spatial species accumulation curves using fixed-focus spatially constrained rarefaction, nearest-centroid expansion, and nearest-neighbor walks with a C++ backend for speed. Supports Hill numbers (q=0,1,2), beta diversity partitioning (turnover/nestedness) at site and pooled resolution, coverage-based rarefaction and extrapolation of alpha and beta diversity, phylogenetic diversity (PD; Faith's PD, EvoHeritage, mean pairwise distance, mean nearest taxon distance), functional diversity accumulation including aggregated functional diversity and intraspecific trait variation, phylogenetic and functional redundancy, interaction network accumulation, diversity-area relationships (DAR), endemism-area curves, sampling-effort correction and fragmentation analysis, species-area relationship (SAR) models based on extreme value theory (EVT), and area-based richness extrapolation via the total-species curve. Total richness is also estimated from frequency counts, including the accumulation rate curve estimator and an estimator for sites sampled without replacement, and shift-and-rotate null models test the position of a sampling design. Multiple starting points (seeds) provide uncertainty quantification. Methods are described in Chao et al. (2014) doi:10.1890/13-0133.1, Baselga (2010) doi:10.1111/j.1466-8238.2009.00490.x, Chao and Jost (2012) doi:10.1890/11-1952.1, Faith (1992) doi:10.1016/0006-3207(92)91201-3, Ma (2018) doi:10.1002/ece3.4425, Borda-de-Agua et al. (2025) doi:10.1038/s41467-025-59239-7, Hanski et al. (2013) doi:10.1073/pnas.1311190110, Jost (2007) doi:10.1890/06-1736.1, Ugland et al. (2003) doi:10.1046/j.1365-2656.2003.00748.x, Chao et al. (2023) doi:10.1002/ecm.1588, Chiu (2023) doi:10.1111/2041-210X.14146, Chiu et al. (2023) doi:10.1098/rstb.2022.0183, Rosindell et al. (2024) doi:10.1093/sysbio/syad072, Wojcik et al. (2024) doi:10.1111/2041-210X.14470, Ridder et al. (2024) doi:10.1111/2041-210X.14443, Jones et al. (2025) doi:10.1111/ddi.70080, and Shestopaloff (2025) doi:10.1007/s10651-025-00644-y.

Author(s)

Maintainer: Gilles Colling gilles.colling051@gmail.com (ORCID) [copyright holder]

Authors:

See Also

Useful links:


Estimate richness with the abundance-based coverage estimator (ACE)

Description

Abundance-based Coverage Estimator (ACE) of total species richness (Chao & Lee 1992). Separates species into rare and abundant groups based on an abundance threshold.

Usage

ace(x, threshold = 10L)

Arguments

x

A site-by-species matrix (abundance data).

threshold

Integer. Abundance threshold separating rare from abundant species. Default 10.

Details

ACE partitions species into rare (abundance \le threshold) and abundant (abundance > threshold) groups. The estimate is:

S_{ACE} = S_{abund} + \frac{S_{rare}}{C_{ACE}} + \frac{f_1}{C_{ACE}} \gamma^2

where C_{ACE} is the sample coverage of rare species and \gamma^2 is the estimated coefficient of variation.

The standard error is the delta-method one of Chao & Lee (1992): the estimate is a function of the frequency counts f_1, \ldots, f_k of the rare species (k the threshold) and of the number of abundant species, which are treated as multinomial over the estimated richness.

Value

An object of class spacc_estimate.

References

Chao, A. & Lee, S.M. (1992). Estimating the number of classes via sample coverage. Journal of the American Statistical Association, 87, 210-217.

See Also

chao1(), chao2()

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
ace(species)


Compute alpha diversity per site

Description

Compute Hill numbers for each site individually.

Usage

alphaDiversity(x, q = c(0, 1, 2), coords = NULL)

Arguments

x

A site-by-species matrix (abundance data).

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

coords

Optional data.frame with columns x and y for spatial mapping. When provided, returns a spacc_alpha object with as_sf() and plot(type = "map") support.

Details

Alpha diversity represents local (within-site) diversity. For Hill numbers:

Value

If coords is NULL, a data.frame with columns for each q value. If coords is provided, a spacc_alpha object.

References

Jost, L. (2007). Partitioning diversity into independent alpha and beta components. Ecology, 88, 2427-2439. doi:10.1890/06-1736.1

See Also

gammaDiversity() for regional diversity, diversityPartition() for full alpha-beta-gamma decomposition

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
alpha <- alphaDiversity(species, q = c(0, 1, 2))
head(alpha)

# Mean alpha diversity
colMeans(alpha)


Compute expected accumulation curves analytically

Description

These methods compute expected species accumulation without simulation. They are faster but don't provide spatial information.


Estimate richness from the accumulation rate curve (ARC)

Description

Estimate total species richness from the rate at which new species appear along a random reordering of the observations (Shestopaloff 2025). The rate curve is extrapolated with three decay curves whose tails give the number of species not yet seen, combined with bounded weights.

Usage

arc(
  x,
  data = c("abundance", "incidence"),
  K = 20L,
  adjust = FALSE,
  n_boot = 2000L,
  parallel = TRUE,
  n_cores = NULL
)

Arguments

x

A site-by-species matrix. For data = "abundance" the columns are pooled into species abundances; for data = "incidence" the matrix is binarized and each species counts the sites it occupies.

data

Character. "abundance" (default) treats every individual as one observation; "incidence" treats every species-site occurrence as one.

K

Integer. Species seen more than K times are left out of the rate curve. Default 20.

adjust

Logical. Apply the smoothing adjustment of Eq. 11 with a log-linear fit to the frequency counts? Default FALSE. See Details.

n_boot

Integer. Parametric bootstrap draws for the interval. Default 2000. 0 returns the point estimate only.

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

Details

Let y_k be the number of species observed k times and N the number of observations of the species with k \le K. Drawing the observations in random order, the expected number of these species seen after n draws is

S(n) = \sum_{k=1}^{K} y_k \left[1 - (1 - n/N)^k\right],

and the accumulation rate is s_n = S(n) - S(n-1), evaluated at up to 1000 points. Three curves are fitted to the tail of s_n by least squares with weights proportional to the squared point index: the log-normal 1 - \Phi((\log n - \mu)/\sigma), the log-logistic 1/(1 + \alpha n^\gamma) and the Weibull \exp(-\lambda n^\gamma), the last on the log scale. Each curve's integral from N to infinity is its number of undetected species; the log-logistic integral is finite only for \gamma > 1.

The estimate combines the three with weights fitted by the squared misfit to s_n plus a penalty on the product of the log-logistic and Weibull weights (Eq. 8), each bounded by caps built from the three estimates and the observed richness (Eq. 7). The undetected species are averaged over fits to the last 100, 95, ..., 70 percent of the curve.

The penalty is there to make the fit prefer either the log-logistic or the Weibull, and gives the loss one local minimum for each. The weights are the end point of the projected gradient flow of the loss started at zero weights, which arc() solves in closed form face by face of the box of admissible weights. This is the minimum the author's reference code reaches (L-BFGS within an augmented Lagrangian, started at zero). In Poisson-Gamma samples of intermediate sparsity it is the log-logistic one, with median bias between -1 and +4 percent; the global minimum of the loss is the Weibull one there, with median bias between -9 and -17 percent (Estimating total richness).

With adjust = TRUE the counts y_1, \dots, y_{k_1} (the first run of positive counts) are mixed half and half with a log-linear fit \log y_k = b_0 + b_1 k, and fully replaced by it; the adjusted estimate is 2 S_{0.5} - S_1. The adjustment assumes the ratios (k+1) y_{k+1} / y_k are linear in k.

The interval comes from a parametric bootstrap of the counts. Their covariance is that of a mixture of 30 Poisson distributions whose weights are fitted to (y_1, \dots, y_K, y_{K+}) by penalised least squares (Eq. 12-15). The penalty is chosen by resampling species: 1500 resamples are ordered by their distance to the left-out species and split into deciles, and the first decile whose out-of-sample error is smallest at a non-zero penalty sets it. n_boot count vectors are drawn from a normal distribution with that covariance, rounded to non-negative integers and re-estimated; the interval is their 2.5 and 97.5 percent quantiles and the standard error their standard deviation. In Poisson-Gamma simulations the 95 percent interval covered the truth in 93 to 96 percent of samples for sparse data and about 89 percent for dense data, where the point estimate is biased upwards (Estimating total richness).

With data = "incidence" the observations are species-site occurrences and y_k becomes Q_k, the number of species found at k sites, the substitution that turns Chao1 into Chao2.

Value

An object of class spacc_estimate with estimator = "ARC". Its details hold undetected (undetected species from each curve) and weights (their weights), both averaged over the curve portions, K, data, penalty (the selected Poisson-mixture penalty) and boot (the bootstrap estimates).

References

Shestopaloff, K. (2025). An accumulation rate curve estimator for total species. Environmental and Ecological Statistics, 32, 311-345. doi:10.1007/s10651-025-00644-y

See Also

chao1(), chao2(), ace()

Examples

set.seed(1)
species <- matrix(rpois(40 * 300, rgamma(300, 0.4, 2)), nrow = 40, byrow = TRUE)
arc(species, n_boot = 0)

arc(species, n_boot = 200)



Convert per-site results to an sf object

Description

Convert metrics to an sf object for spatial analysis and integration with the areaOfEffect package.

Usage

as_sf(x, crs = NULL)

Arguments

x

A spacc_metrics object.

crs

Coordinate reference system. Default NULL (no CRS). Use EPSG codes like 4326 for WGS84 or 32631 for UTM zone 31N.

Value

An sf object with POINT geometries and metric columns.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
metrics <- spaccMetrics(species, coords)
if (requireNamespace("sf", quietly = TRUE)) {
  metrics_sf <- as_sf(metrics)
}



Convert an accumulation curve from another package to a spacc object

Description

Bring an existing species accumulation curve into the spacc object system so it can be summarised, plotted, extrapolated and compared with compare() alongside spatial curves.

Usage

as_spacc(x, ...)

## Default S3 method:
as_spacc(x, ...)

## S3 method for class 'specaccum'
as_spacc(x, ...)

## S3 method for class 'numeric'
as_spacc(x, ...)

## S3 method for class 'data.frame'
as_spacc(x, column = NULL, ...)

Arguments

x

An object to convert: a specaccum object from vegan::specaccum(), a numeric vector holding one accumulation curve, or a data frame with such a curve in one column (for example the output of Rarefy::directionalSAC() or Rarefy::rare_alpha()).

...

Ignored, for method extensibility.

column

For a data frame, the name of the column holding the curve. NULL (default) uses N_SCR (the spatially constrained curve of Rarefy::directionalSAC()) or Rarefaction (Rarefy::rare_alpha()), whichever is present.

Details

A specaccum object built with method = "random" stores one richness curve per permutation in its perm matrix. Those curves become the rows of the returned curves matrix and behave exactly like spacc seeds, so the across-curve confidence band and the compare() permutation, bootstrap, and AUC tests carry over unchanged. A specaccum object without a permutation matrix (for example method = "exact" or "collector"), a numeric vector and a data frame column each contribute a single mean curve, entry k being the value after k sites.

Rarefy::directionalSAC(community, gradient) with a site distance matrix as gradient orders the sites by distance from each plot in turn and averages the collector curves; this is spacc(x, coords, method = "knn", focal_points = coords), so the two curves agree up to the order of sites at tied distances.

Coordinates cannot be recovered from these objects, so the result carries no coords: it is a curve container for plotting and comparison, not a re-runnable spatial object.

Value

An object of class spacc with print(), summary(), plot(), as.data.frame(), and compare() support.

References

Thouverai, E., Pavoine, S., Tordoni, E., Chiarucci, A., Ricotta, C., Rocchini, D. & Bacaro, G. (2026). Rarefy: an R package for the calculation of taxonomic, functional and phylogenetic sample-based spatially explicit rarefaction curves. Ecological Informatics, 103803. doi:10.1016/j.ecoinf.2026.103803

See Also

compare() to test a converted curve against a spatial one.

Examples


if (requireNamespace("vegan", quietly = TRUE)) {
  data(BCI, package = "vegan")
  classic <- vegan::specaccum(BCI, method = "random")
  sp <- as_spacc(classic)
  summary(sp)
  plot(sp)
}

as_spacc(c(5, 8, 10, 11, 12))


Plot spacc objects with ggplot2 autoplot()

Description

ggplot2::autoplot() methods for spacc objects. Each one calls the corresponding plot() method, which already returns a ggplot2 object.

Usage

## S3 method for class 'spacc'
autoplot(object, ...)

Arguments

object

A spacc object.

...

Additional arguments passed to the corresponding plot() method.

Value

A ggplot2 object.

Examples


if (requireNamespace("ggplot2", quietly = TRUE)) {
  coords <- data.frame(x = runif(30), y = runif(30))
  species <- matrix(rbinom(30 * 15, 1, 0.3), nrow = 30)
  sac <- spacc(species, coords, n_seeds = 5, progress = FALSE)
  ggplot2::autoplot(sac)
}



Fit distance-decay models to pairwise beta dissimilarity

Description

Compute the distance-decay of community similarity by fitting models to pairwise beta dissimilarity as a function of geographic distance.

Usage

betaDecay(
  x,
  coords,
  index = c("sorensen", "jaccard"),
  model = c("all", "exponential", "power", "linear"),
  distance = c("euclidean", "haversine"),
  n_bins = 50L,
  progress = TRUE
)

Arguments

x

A site-by-species matrix (presence/absence or abundance), or a spacc object (will use its stored coordinates).

coords

A data.frame with columns x and y, or a spacc_dist object.

index

Character. Dissimilarity index: "sorensen" (default) or "jaccard".

model

Character. Decay model to fit: "exponential", "power", "linear", or "all" (default). When "all", fits all three and selects the best by AIC.

distance

Character. Distance method: "euclidean" (default) or "haversine".

n_bins

Integer. Number of distance bins for binned means in plots. Default 50.

progress

Logical. Show progress messages? Default TRUE.

Details

Three decay models are available:

Each model is fitted by least squares to the dissimilarities of all pairs at positive distance, so the AIC values of the three models compare fits to the same data, as in betapart::decay.model().

The half-life (exponential model) is the distance at which similarity decays to half its initial value: d_{1/2} = \ln(2) / b.

Value

An object of class spacc_beta_decay containing:

pairs

Data.frame with columns distance, dissimilarity, site_i, site_j

fits

Named list of fitted model objects

best_model

Name of best model by AIC

half_life

Distance at which similarity halves (exponential model only)

coefficients

Data.frame of model coefficients and AIC

index

Dissimilarity index used

n_sites

Number of sites

n_pairs

Number of pairwise comparisons

References

Nekola, J.C. & White, P.S. (1999). The distance decay of similarity in biogeography and ecology. Journal of Biogeography, 26, 867-878.

Morlon, H., Chuyong, G., Condit, R., et al. (2008). A general framework for the distance-decay of similarity in ecological communities. Ecology Letters, 11, 904-917.

See Also

spaccBeta() for spatial beta diversity accumulation, distanceDecay() for species similarity decay

Examples


coords <- data.frame(x = runif(30), y = runif(30))
species <- matrix(rbinom(30 * 20, 1, 0.3), nrow = 30)

bd <- betaDecay(species, coords)
print(bd)
plot(bd)



Estimate richness with the bootstrap estimator

Description

Bootstrap estimator of total species richness (Smith & van Belle 1984). Uses species detection probabilities to estimate undetected species.

Usage

bootstrap_richness(x)

Arguments

x

A site-by-species matrix (presence/absence or abundance). Automatically binarized.

Details

The bootstrap estimator is:

S_{boot} = S_{obs} + \sum_{i=1}^{S_{obs}} (1 - p_i)^n

where p_i is the proportion of sites where species i occurs. It is the expectation, over resamples of the n sites with replacement, of the species a resample misses, so no resampling is needed.

The variance is the closed form of Smith & van Belle (1984),

var(S_{boot}) = \sum_i (1 - p_i)^n \left(1 - (1 - p_i)^n\right) + \sum_{i \ne j} \left(q_{ij}^n - (1 - p_i)^n (1 - p_j)^n\right),

with q_{ij} the proportion of sites where neither species i nor j occurs. The interval is the estimate plus or minus 1.96 standard errors, with the lower bound no smaller than the observed richness.

Value

An object of class spacc_estimate.

References

Smith, E.P. & van Belle, G. (1984). Nonparametric estimation of species richness. Biometrics, 40, 119-129.

See Also

jackknife(), chao2()

Examples

species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
bootstrap_richness(species)


Combine spacc objects

Description

Combine spacc objects

Usage

## S3 method for class 'spacc'
c(...)

Arguments

...

Named spacc objects to combine into a grouped spacc.

Value

A grouped spacc object with per-group curves.


Combine spacc_beta objects

Description

Combine multiple spacc_beta objects by stacking their curve matrices. All objects must have the same number of sites and index.

Usage

## S3 method for class 'spacc_beta'
c(...)

Arguments

...

spacc_beta objects to combine.

Value

A combined spacc_beta object with more seeds.


Combine spacc_coverage objects

Description

Combine multiple spacc_coverage objects by stacking their curve matrices. All objects must have the same number of sites.

Usage

## S3 method for class 'spacc_coverage'
c(...)

Arguments

...

spacc_coverage objects to combine.

Value

A combined spacc_coverage object with more seeds.


Combine spacc_hill objects

Description

Combine multiple spacc_hill objects by stacking their curve matrices. All objects must have the same number of sites.

Usage

## S3 method for class 'spacc_hill'
c(...)

Arguments

...

spacc_hill objects to combine.

Value

A combined spacc_hill object with more seeds.


Estimate richness with Chao1

Description

Estimate total species richness from abundance data using the Chao1 estimator (Chao 1984). Uses the number of singletons and doubletons to estimate undetected species.

Usage

chao1(x)

Arguments

x

A site-by-species matrix (abundance data). Columns are pooled across sites.

Details

The Chao1 estimator is:

S_{Chao1} = S_{obs} + \frac{f_1^2}{2 f_2}

where f_1 is the number of singletons (species with total abundance 1) and f_2 is the number of doubletons (abundance 2).

When f_2 = 0, the bias-corrected form is used:

S_{Chao1} = S_{obs} + \frac{f_1 (f_1 - 1)}{2}

Value

An object of class spacc_estimate with components:

estimator

Name of the estimator ("chao1")

estimate

Estimated total richness

se

Standard error of the estimate

lower

Lower 95 percent confidence bound

upper

Upper 95 percent confidence bound

S_obs

Observed species richness

details

List with f1 (singletons) and f2 (doubletons)

References

Chao, A. (1984). Nonparametric estimation of the number of classes in a population. Scandinavian Journal of Statistics, 11, 265-270.

Chao, A. (1987). Estimating the population size for capture-recapture data with unequal catchability. Biometrics, 43, 783-791.

See Also

chao2() for incidence-based estimation, ace() for abundance-based coverage estimator

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
chao1(species)


Estimate richness with Chao2

Description

Estimate total species richness from incidence (presence/absence) data using the Chao2 estimator (Chao 1987).

Usage

chao2(x, n_units = NULL)

Arguments

x

A site-by-species matrix (presence/absence or abundance). Automatically binarized.

n_units

Total number of sampling units in the study region, when the rows of x are a sample drawn without replacement from a finite set of units (atlas cells, a plot network). NULL (default) or Inf assumes sampling with replacement and gives Chao2; a finite value gives the MoRE estimator of Chiu (2023).

Details

The Chao2 estimator is the incidence-based analogue of Chao1:

S_{Chao2} = S_{obs} + \frac{t-1}{t} \frac{Q_1^2}{2 Q_2}

where t is the number of sites, Q_1 is the number of uniques (species found at exactly 1 site) and Q_2 is the number of duplicates (species found at exactly 2 sites).

Chao2 assumes the sites are drawn with replacement, or from an effectively infinite set of units. When they are a large fraction w = t / T of a finite set of T units it overestimates richness and does not reach the true richness as w \to 1. With n_units = T, chao2() returns the moment-based estimator for sampling without replacement (MoRE, Chiu 2023, Eq. 5):

S_{MoRE} = S_{obs} + \frac{t-1}{t} \frac{(1-w) Q_1^2}{Q_2 + w (Q_1 - Q_2)^+}

where (A)^+ is A for A > 0 and 1 otherwise; for Q_2 = 0 the undetected term is \frac{t-1}{t} \frac{1-w}{w} (Q_1 - 1). MoRE equals the observed richness at w = 1. Its standard error is the delta-method variance of Chiu (2023) and the interval is the log-normal one used for Chao2.

Value

An object of class spacc_estimate.

References

Chao, A. (1987). Estimating the population size for capture-recapture data with unequal catchability. Biometrics, 43, 783-791.

Chiu, C.-H. (2023). A species richness estimator for sample-based incidence data sampled without replacement. Methods in Ecology and Evolution, 14, 2482-2493. doi:10.1111/2041-210X.14146

See Also

chao1() for abundance-based estimation

Examples

species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
chao2(species)
# the 50 sites are 80% of a 62-cell grid
chao2(species, n_units = 62)


Compute the Coleman expected accumulation curve

Description

Compute the expected species accumulation curve using the Coleman method (Coleman et al. 1982). This is an analytical formula, no simulation needed.

Usage

coleman(x)

Arguments

x

A site-by-species matrix (presence/absence or abundance).

Value

A data.frame with columns: sites, expected, sd

References

Coleman, B.D., Mares, M.A., Willig, M.R. & Hsieh, Y.H. (1982). Randomness, area, and species richness. Ecology, 63, 1121-1133.


Compute the collector's curve in data order

Description

Compute the species accumulation curve in the order sites appear in the data (no randomization). Useful for understanding how data was collected.

Usage

collector(x)

Arguments

x

A site-by-species matrix.

Value

A data.frame with columns: sites, species


Compare two accumulation curves

Description

Test whether two species accumulation curves differ significantly.

Usage

compare(
  x,
  y,
  method = c("permutation", "bootstrap", "auc"),
  normalize = FALSE,
  n_perm = 999L,
  ...
)

Arguments

x

A spacc object.

y

A spacc object.

method

Character. Comparison method: "permutation" (default), "bootstrap", or "auc" (area under curve difference, no test). See Details.

normalize

Logical. If TRUE, each seed's curve is divided by its final value before computing AUC, so that curves are compared on a [0, 1] scale (proportion of total species). This compares the shape of accumulation rather than absolute species counts. Default FALSE.

n_perm

Integer. Number of permutations/bootstrap replicates. Default 999.

...

Additional arguments passed to comparison methods.

Details

The area under the mean curve is the mean over seeds of each seed's own area, so both tests compare the mean per-seed area of the two objects.

"permutation" shuffles the seeds between the two objects and recomputes the area difference n_perm times. It tests whether the two sets of curves come from the same distribution.

"bootstrap" is the bootstrap test of equal means of Efron and Tibshirani (1993, Algorithm 16.2, p. 224), which does not assume that the two objects have the same variance between seeds. The per-seed areas of each object are shifted to the mean of the combined areas, so that the null hypothesis holds, and resampled with replacement within each object n_perm times. The statistic is the area difference divided by its standard error, sqrt(var_x / n_x + var_y / n_y) (their Eq. 16.5). Efron and Tibshirani count the replicates at or above the observed statistic, a one-sided test (Eq. 16.7); compare() counts them in absolute value, so the test is two-sided like the permutation test. It needs at least two seeds in each object.

Both p-values are two-sided and computed as (1 + b) / (n_perm + 1), where b counts the replicates whose statistic is at least as large in absolute value as the observed one (Davison and Hinkley 1997, Eqs. 4.11 and 4.13, pp. 141 and 148; Phipson and Smyth 2010, Sections 4 and 5). The smallest possible value is 1 / (n_perm + 1).

Value

An object of class spacc_comp containing:

x_name, y_name

Names of compared objects

auc_diff

Difference in area under curve

p_value

Two-sided p-value of the permutation or bootstrap test; NA for method = "auc"

auc_diff_ci

For method = "bootstrap", the 95% percentile bootstrap interval of the area difference; NULL otherwise

saturation_diff

Difference in saturation points

method

Comparison method used

normalized

Whether curves were normalized before comparison

References

Colwell, R.K., Mao, C.X. & Chang, J. (2004). Interpolating, extrapolating, and comparing incidence-based species accumulation curves. Ecology, 85, 2717-2727.

Gotelli, N.J. & Colwell, R.K. (2011). Estimating species richness. In: Biological Diversity: Frontiers in Measurement and Assessment, pp. 39-54. Oxford University Press.

Efron, B. & Tibshirani, R.J. (1993). An Introduction to the Bootstrap. Chapman & Hall, New York.

Davison, A.C. & Hinkley, D.V. (1997). Bootstrap Methods and their Application. Cambridge University Press.

Phipson, B. & Smyth, G.K. (2010). Permutation p-values should never be zero: calculating exact p-values when permutations are randomly drawn. Statistical Applications in Genetics and Molecular Biology, 9, Article 39. doi:10.2202/1544-6115.1585

Examples


coords <- data.frame(x = runif(50), y = runif(50))
sp_a <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sp_b <- matrix(rbinom(50 * 30, 1, 0.5), nrow = 50)

sac_a <- spacc(sp_a, coords, n_seeds = 10)
sac_b <- spacc(sp_b, coords, n_seeds = 10)
comp <- compare(sac_a, sac_b)
print(comp)



Compare asymptotic accumulation models

Description

Fit all (or a subset of) asymptotic species-area models and compare them using AIC, BIC, delta-AIC, and Akaike weights.

Usage

compareModels(
  object,
  models = c("michaelis-menten", "lomolino", "asymptotic", "weibull", "logistic", "evt"),
  ...
)

Arguments

object

A spacc object.

models

Character vector of models to fit. Defaults to all six: "michaelis-menten", "lomolino", "asymptotic", "weibull", "logistic", "evt".

...

Additional arguments passed to extrapolate().

Value

An object of class spacc_model_compare containing:

table

Data frame with model comparison statistics

fits

Named list of spacc_fit objects

best_model

Name of the best model by AIC

data

Mean-curve data frame used for fitting

spacc

Original spacc object

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords)
cm <- compareModels(sac)
print(cm)



Compute a sample completeness profile across diversity orders

Description

Compute the ratio of observed to estimated diversity across diversity orders, measuring how complete a sample is at each level of the Hill number spectrum.

Usage

completenessProfile(x, q = seq(0, 2, by = 0.2), coords = NULL)

Arguments

x

A site-by-species matrix (abundance data).

q

Numeric vector. Orders of diversity to evaluate. Default seq(0, 2, by = 0.2).

coords

Optional data.frame with columns x and y for spatial mapping. When provided, enables plot(type = "map") and as_sf().

Details

Sample completeness at order q is:

C_q = \frac{D_q^{obs}}{D_q^{est}}

where D_q^{obs} is the observed Hill number and D_q^{est} is the estimated asymptotic Hill number.

Completeness near 1 means the sample captures most of the true diversity at that order. Completeness typically increases with q because dominant species are detected early.

Asymptotic estimators used:

When coords is provided, per-site completeness is computed by treating each site's abundance vector as an independent sample.

Value

An object of class spacc_completeness containing:

completeness

Named numeric vector of completeness ratios per q

observed

Named numeric vector of observed Hill numbers per q

estimated

Named numeric vector of estimated asymptotic Hill numbers per q

per_site

Matrix of per-site completeness (sites x q values), or NULL

q

Vector of diversity orders

coords

Coordinates if provided

n_sites

Number of sites

n_species

Number of species

References

Chao, A. & Jost, L. (2012). Coverage-based rarefaction and extrapolation: standardizing samples by completeness rather than size. Ecology, 93, 2533-2547.

Chao, A. & Jost, L. (2015). Estimating diversity and entropy profiles via discovery rates of new species. Methods in Ecology and Evolution, 6, 873-882.

See Also

diversityProfile() for observed diversity profiles, chao1() for richness estimation

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
comp <- completenessProfile(species)
print(comp)


plot(comp)



Compute a confidence interval for an extrapolated asymptote

Description

Returns the calibrated bootstrap interval stored on the fit by default. With method = "profile" the (over-confident) nls profile interval is computed instead. The interval is for the asymptote parameter; see the bias caveat in extrapolate().

Usage

## S3 method for class 'spacc_fit'
confint(object, parm, level = 0.95, method = c("stored", "profile"), ...)

Arguments

object

A spacc_fit object.

parm

Ignored; the asymptote ("a") is always returned.

level

Confidence level. Recomputed from stored bootstrap draws.

method

"stored" (default) or "profile".

...

Passed to stats::confint() when method = "profile".

Value

A 1-row matrix with the lower and upper bound for a.


Relate diversity to cumulative area (DAR)

Description

Diversity against cumulative area along a spatial accumulation, for Hill numbers (Ma 2018) or for any curve spacc computes: species richness, phylogenetic and functional metrics, redundancy.

Usage

dar(x, ...)

## Default S3 method:
dar(
  x,
  coords,
  q = c(0, 1, 2),
  n_seeds = 50L,
  method = "knn",
  area_method = c("convex_hull", "voronoi", "count"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL,
  ...
)

## S3 method for class 'spacc'
dar(x, area_method = c("convex_hull", "voronoi", "count"), ...)

## S3 method for class 'spacc_hill'
dar(x, area_method = c("convex_hull", "voronoi", "count"), ...)

## S3 method for class 'spacc_phylo'
dar(x, area_method = c("convex_hull", "voronoi", "count"), ...)

## S3 method for class 'spacc_func'
dar(x, area_method = c("convex_hull", "voronoi", "count"), ...)

## S3 method for class 'spacc_redundancy'
dar(x, area_method = c("convex_hull", "voronoi", "count"), ...)

Arguments

x

A site-by-species matrix (abundance data recommended), or a curve object: spacc, spacc_hill, spacc_phylo, spacc_func or spacc_redundancy. A matrix is first passed to spaccHill() with q.

...

Arguments passed to methods.

coords

A data.frame with columns x and y, or a spacc_dist object (matrix input only).

q

Numeric vector. Diversity orders (matrix input only). Default c(0, 1, 2).

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

area_method

Character. How to measure the area covered by the first k sites of an order: "convex_hull" (area of their convex hull, 0 until three sites span a polygon), "voronoi" (summed area of their Voronoi cells within the bounding box of all sites) or "count" (number of sites). Areas are in squared coordinate units. Default "convex_hull".

distance

Character. Distance method. Default "euclidean".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

The DAR (Ma, 2018) generalizes the SAR by replacing species richness (q=0) with Hill numbers of any order. This reveals how different facets of diversity scale with area:

The area is accumulated along the same site orders as the diversity curve, so any curve object gives its own diversity-area relationship: functional richness, dispersion and other facets can scale with area differently from richness (Dias et al. 2025). The power-law exponent z is the slope of log mean diversity against log mean area over the steps where both are positive.

Value

An object of class spacc_dar containing:

curves

Named list of diversity curves (n_seeds x n_sites), one per metric or order

metric

Names of the curves

area

Matrix of cumulative areas (n_seeds x n_sites)

power_law

Data frame with the power-law fit D = c A^z of each mean curve (metric, c, z)

q

Diversity orders for Hill-number input, else NULL

area_method

Method used for area estimation

source

Class of the curve object the DAR was built from

object

That curve object

References

Ma, Z.S. (2018). DAR (diversity-area relationship): extending classic SAR for biodiversity and biogeography analyses. Ecology and Evolution, 8, 10023-10038.

Arrhenius, O. (1921). Species and area. Journal of Ecology, 9, 95-99.

Dias, R.A., Bastazini, V.A.G., Gianuca, A.T. & Matthews, T.J. (2025). The spatial scaling of multiple dimensions of functional diversity in habitat islands. Functional Ecology. doi:10.1111/1365-2435.70158

See Also

spaccHill(), spaccFunc(), spaccPhylo(), extrapolate()

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rpois(50 * 30, 2), nrow = 50)

d <- dar(species, coords, q = c(0, 1, 2))
plot(d)

traits <- matrix(rnorm(30 * 2), nrow = 30)
func <- spaccFunc(species, coords, traits, metric = c("fdis", "fric"))
dar(func)



Count species within growing distances of focal points

Description

Analyze how species richness changes with distance from focal points.

Usage

distanceDecay(
  x,
  coords,
  n_seeds = 50L,
  breaks = NULL,
  distance = c("euclidean", "haversine"),
  progress = TRUE,
  seed = NULL
)

Arguments

x

A site-by-species matrix.

coords

A data.frame with x and y columns.

n_seeds

Integer. Number of focal points.

breaks

Numeric vector. Distance thresholds. Default auto-calculated.

distance

Character. Distance method.

progress

Logical. Show progress?

seed

Integer. Random seed.

Value

An object of class spacc_decay with distance-species relationships.

References

Nekola, J.C. & White, P.S. (1999). The distance decay of similarity in biogeography and ecology. Journal of Biogeography, 26, 867-878.

Soininen, J., McDonald, R. & Hillebrand, H. (2007). The distance decay of similarity in ecological communities. Ecography, 30, 3-12.


Compute a distance matrix between sites

Description

Pre-compute pairwise distances between sites for reuse across multiple spacc() calls. Supports sf objects with accurate geodesic distances for global-scale studies.

Usage

distances(x, method = NULL, fun = NULL, which = NULL)

Arguments

x

Site locations. Can be:

  • A data.frame with columns x and y

  • An sf object with POINT geometries

  • An sfc_POINT object

method

Character. Distance method:

  • "euclidean": Euclidean distance (for projected coordinates)

  • "haversine": Great-circle distance (for lat/lon, fast approximation

  • "geodesic": Accurate ellipsoidal distance via sf/S2 (for global scale) Default is auto-detected from CRS when using sf objects.

fun

Optional custom distance function. Must take two coordinate vectors (x, y) and return a distance matrix. Overrides method.

which

For sf objects, column name containing the geometry. Default uses active geometry.

Details

For continental and global-scale studies, use sf objects with geographic CRS (e.g., EPSG:4326). The function will automatically use accurate geodesic distances via the S2 spherical geometry library.

For smaller study areas with projected coordinates (UTM, etc.), Euclidean distance is appropriate and faster.

Value

An object of class spacc_dist containing the distance matrix with coordinates stored as an attribute.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
d <- distances(coords)

# Reuse for multiple analyses
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, d)



Partition diversity into alpha, beta and gamma components

Description

Decompose regional (gamma) diversity into local (alpha) and turnover (beta) components using multiplicative partitioning of Hill numbers.

Usage

diversityPartition(x, q = c(0, 1, 2), weights = "equal", coords = NULL)

Arguments

x

A site-by-species matrix (abundance data).

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

weights

Character or numeric. Site weights, used for alpha and for gamma:

  • "equal": Equal weights (default)

  • "proportional": Weights proportional to site abundance

  • Numeric vector of custom weights

coords

Optional data.frame with columns x and y for spatial mapping. When provided, enables as_sf() and plot(type = "map").

Details

This function implements Jost (2007) multiplicative partitioning:

\gamma = \alpha \times \beta

Where:

Alpha and gamma use the same site weights w_j. Gamma is the Hill number of the weighted mean relative abundances \sum_j w_j p_{ij}. Alpha is (Jost 2007, Eq. 11a, p. 2431)

{}^qD_\alpha = \left(\frac{\sum_j w_j^q \sum_i p_{ij}^q}{\sum_j w_j^q}\right)^{1/(1-q)},

and \exp(\sum_j w_j H_j) with the Shannon entropies H_j at q = 1 (Eq. 11b); at q = 0 the weights drop out and alpha is the mean site richness. With equal weights every site counts the same whatever its number of individuals. With "proportional" weights gamma is the Hill number of the pooled counts, as returned by gammaDiversity(). With unequal weights alpha never exceeds gamma only at q = 0 and q = 1; at other orders it can (Jost 2007, p. 2433).

Beta diversity is interpreted as the effective number of communities:

Value

An object of class spacc_partition containing:

alpha

Mean alpha diversity (effective number of species per site)

beta

Beta diversity (effective number of communities)

gamma

Gamma diversity (regional species pool)

q

Orders of diversity

n_sites

Number of sites

n_species

Total species count

References

Jost, L. (2007). Partitioning diversity into independent alpha and beta components. Ecology, 88, 2427-2439. doi:10.1890/06-1736.1

Chao, A., Chiu, C.H. & Jost, L. (2014). Unifying species diversity, phylogenetic diversity, functional diversity, and related similarity and differentiation measures through Hill numbers. Annual Review of Ecology, Evolution, and Systematics, 45, 297-324.

See Also

alphaDiversity(), gammaDiversity(), spaccBeta() for spatial beta diversity accumulation

Examples

# Simulated community data
species <- matrix(rpois(50 * 30, 2), nrow = 50)

# Partition diversity
part <- diversityPartition(species, q = c(0, 1, 2))
print(part)

# Beta near 1 = homogeneous region
# Beta near n_sites = heterogeneous region


Compute a diversity profile across orders q

Description

Compute Hill numbers across a continuous range of diversity orders (q), producing a diversity profile for each site and the regional pool.

Usage

diversityProfile(
  x,
  q = seq(0, 3, by = 0.1),
  type = c("both", "per_site", "regional"),
  traits = NULL,
  tree = NULL,
  dist_method = c("euclidean", "gower"),
  normalize = TRUE,
  coords = NULL
)

Arguments

x

A site-by-species matrix (abundance data). Column names must match trait row names / tree tip labels when traits / tree is supplied.

q

Numeric vector. Orders of diversity to evaluate. Default seq(0, 3, by = 0.1).

type

Character. What to compute: "per_site" (per-site profiles), "regional" (pooled gamma), or "both" (default).

traits

Optional species-by-traits data.frame (row names matching species). When supplied, functional Hill numbers (Leinster & Cobbold 2012) are computed.

tree

Optional ape::phylo object. When supplied, phylogenetic Hill numbers (Chao et al. 2010) are computed. Supply at most one of traits or tree.

dist_method

Character. Trait distance for the functional profile: "euclidean" (default) or "gower". Ignored unless traits is supplied.

normalize

Logical. Normalize trait distances to [0, 1]? Default TRUE. Ignored unless traits is supplied.

coords

Optional data.frame with columns x and y for spatial mapping. When provided, enables plot(type = "map").

Details

A diversity profile plots effective number of species as a function of the order q. The key property is that Hill numbers are non-increasing in q: D_q \ge D_{q'} for q \le q'.

Supplying traits computes functional Hill numbers via a trait-similarity matrix (Leinster & Cobbold 2012); supplying tree computes phylogenetic Hill numbers weighted by branch length (Chao et al. 2010). Both return a spacc_profile whose profile_type records which was computed.

Value

An object of class spacc_profile containing:

per_site

Matrix of per-site diversity (sites x q values), or NULL

regional

Named numeric vector of gamma diversity per q, or NULL

q

Vector of diversity orders used

coords

Coordinates if provided

n_sites

Number of sites

n_species

Number of species

References

Leinster, T. & Cobbold, C.A. (2012). Measuring diversity: the importance of species similarity. Ecology, 93, 477-489.

Chao, A., Chiu, C.H. & Jost, L. (2014). Unifying species diversity, phylogenetic diversity, functional diversity, and related similarity and differentiation measures through Hill numbers. Annual Review of Ecology, Evolution, and Systematics, 45, 297-324.

See Also

alphaDiversity() for per-site values at specific q, gammaDiversity() for regional diversity, evenness() for evenness profiles

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
prof <- diversityProfile(species)
print(prof)


plot(prof)

# Functional profile (pass a species-by-traits data.frame)
colnames(species) <- paste0("sp", 1:30)
traits <- data.frame(size = rnorm(30), row.names = paste0("sp", 1:30))
fp <- diversityProfile(species, traits = traits)



Compute evenness profiles across sites

Description

Compute species evenness across sites using Hill-based, Pielou, or Simpson evenness measures.

Usage

evenness(
  x,
  q = seq(0.1, 3, by = 0.1),
  type = c("hill", "pielou", "simpson"),
  coords = NULL
)

Arguments

x

A site-by-species matrix (abundance data).

q

Numeric vector. Orders of diversity for Hill evenness. Default seq(0.1, 3, by = 0.1). Note: q = 0 is excluded by default because Hill evenness at q = 0 is trivially S/S = 1.

type

Character. Evenness type: "hill" (Hill evenness E_q = D_q / D_0, default), "pielou" (Pielou's J = log(D_1) / log(S)), or "simpson" (Simpson evenness = (1/D_2) / S).

coords

Optional data.frame with columns x and y for spatial mapping. When provided, enables plot(type = "map").

Details

All evenness measures are bounded in [0, 1]:

Hill evenness (Jost 2010):

E_q = D_q / D_0

This divides the effective number of species at order q by species richness.

Pielou's J (Pielou 1966):

J = \frac{\log(D_1)}{\log(S)} = \frac{H'}{\log(S)}

Simpson evenness:

E_{1/D} = \frac{1}{D_2 \cdot S}

Value

An object of class spacc_evenness containing:

per_site

Matrix or vector of per-site evenness values

regional

Regional (pooled) evenness

q

Orders used (for Hill type)

type

Evenness type

coords

Coordinates if provided

n_sites

Number of sites

n_species

Number of species

References

Jost, L. (2010). The relation between evenness and diversity. Diversity, 2, 207-232.

Pielou, E.C. (1966). The measurement of diversity in different types of biological collections. Journal of Theoretical Biology, 13, 131-144.

See Also

diversityProfile() for Hill number profiles, alphaDiversity() for raw diversity values

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)

# Hill evenness profile
ev <- evenness(species)
print(ev)

# Pielou's J
ev_j <- evenness(species, type = "pielou")
print(ev_j)


Extrapolate total species richness

Description

Fit an asymptotic model to the spatial accumulation curve and estimate total species richness beyond the observed sampling effort.

Usage

extrapolate(
  object,
  model = c("michaelis-menten", "lomolino", "asymptotic", "weibull", "logistic", "evt"),
  interval = c("bootstrap", "profile", "none"),
  R = 200L,
  level = 0.95,
  compare = TRUE,
  n_units = NULL,
  warn_ratio = 2,
  ...
)

Arguments

object

A spacc object.

model

Character. Model to fit: "michaelis-menten" (default), "lomolino", "asymptotic", "weibull", "logistic", or "evt" (Extreme Value Theory, Borda-de-Agua et al. 2025).

interval

Character. How to build the asymptote confidence interval: "bootstrap" (default) refits the model across resampled seed curves and takes percentile bounds; "profile" uses the (over-confident) nls profile interval on the mean-curve fit; "none" skips it.

R

Integer. Number of bootstrap refits when interval = "bootstrap". Default 200.

level

Numeric. Confidence level for the interval. Default 0.95.

compare

Logical. If TRUE (default) and the object carries incidence frequencies, compare the asymptote to the nonparametric chao2() / iChao2() estimates and flag large disagreement.

n_units

Total number of sampling units in the region when the sites are drawn without replacement from a finite set. With compare = TRUE the asymptote is then also compared with the MoRE estimator (chao2(x, n_units = ), Chiu 2023), which is the reference for the disagreement warning. Default NULL (sampling with replacement).

warn_ratio

Numeric. Warn when the fitted asymptote exceeds the observed richness by more than this factor. Default 2. Set to Inf to silence.

...

Additional arguments passed to stats::nls().

Value

An object of class spacc_fit containing:

asymptote

Estimated total species richness (asymptote of the model)

asymptote_ci

Confidence interval for the asymptote

model

Model name

interval

Interval method used

fit

The nls fit object

aic

AIC of the model

gof

List with residual rmse and relative rmse_rel over the observed range

compare

Nonparametric chao2 / iChao2 estimates, and MoRE when n_units is given, if available

boot

Bootstrap coefficient draws, if interval = "bootstrap"

Bias caveat

The asymptote is a parametric extrapolation of the accumulation curve. On clustered or strongly under-sampled presence-absence data it tends to overestimate true richness, sometimes substantially, because the curve is far from saturation. The bootstrap interval quantifies the uncertainty of the fitted asymptote (curve-fit and across-seed variability) and is much wider than the nls profile interval, but it is not a calibrated interval for true total richness: it is centred on a possibly biased point estimate. For calibrated total-richness estimates prefer the nonparametric estimators chao2() / iChao2(), which are unbiased on the same data. The printout shows their values alongside the asymptote for comparison.

References

Lomolino, M.V. (2000). Ecology's most general, yet protean pattern: the species-area relationship. Journal of Biogeography, 27, 17-26.

Flather, C.H. (1996). Fitting species-accumulation functions and assessing regional land use impacts on avian diversity. Journal of Biogeography, 23, 155-168.

Borda-de-Agua, L., Whittaker, R.J., Cardoso, P., et al. (2025). Extreme value theory explains the topography and scaling of the species-area relationship. Nature Communications, 16, 5346.

See Also

extrapolateArea() for area-based extrapolation to a region larger than the one sampled; chao2(), iChao2() for nonparametric richness.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords)
fit <- extrapolate(sac)
print(fit)



Extrapolate richness to a larger area (Ugland T-S curve)

Description

Estimate species richness for a spatial extent larger than the one sampled, using the total-species (T-S) curve of Ugland, Gray & Ellingsen (2003). Sites are partitioned into spatial subareas; the T-S curve is the expected total richness of random combinations of subareas plotted against their (convex-hull) area; an asymptotic model is fitted to that curve and extrapolated to a target area, with a site-bootstrap confidence interval.

Usage

extrapolateArea(
  x,
  coords,
  target_area = NULL,
  n_subareas = 10L,
  model = c("michaelis-menten", "asymptotic", "weibull", "lomolino", "logistic"),
  n_combos = 30L,
  R = 200L,
  level = 0.95,
  seed = NULL,
  progress = TRUE
)

Arguments

x

A site-by-species matrix (presence/absence or abundance; binarized).

coords

A two-column matrix or data frame of site coordinates (x, y).

target_area

Numeric. Area to extrapolate to, in the squared units of coords. Defaults to twice the observed (convex-hull) area.

n_subareas

Integer. Number of spatial subareas to partition sites into (k-means on coordinates). Default 10; must be between 4 and the number of sites.

model

Character. Area model to fit: "michaelis-menten" (default), "asymptotic", "weibull", "lomolino", or "logistic".

n_combos

Integer. Number of random subarea combinations averaged per T-S point (all combinations are used when there are fewer). Default 30.

R

Integer. Number of site-bootstrap replicates for the confidence interval. Default 200.

level

Numeric. Confidence level. Default 0.95.

seed

Optional integer for reproducibility.

progress

Logical. Show a progress message. Default TRUE.

Details

Unlike extrapolate(), which extends the curve in sample count, this answers "how many species in a region of a given area", including areas beyond the sampled extent.

Value

An object of class spacc_area with components:

ts_curve

Data frame of the T-S curve (n_sub, area, richness, richness_sd)

fit

The fitted nls area model

observed_area, observed_richness

Convex-hull area and richness of the full sample

target_area

Area extrapolated to

predicted_richness, predicted_ci

Extrapolated richness and its bootstrap interval

asymptote, asymptote_ci

Model asymptote and its bootstrap interval

References

Ugland, K.I., Gray, J.S. & Ellingsen, K.E. (2003). The species-accumulation curve and estimation of species richness. Journal of Animal Ecology, 72, 888-897. doi:10.1046/j.1365-2656.2003.00748.x

See Also

extrapolate() for sample-count extrapolation; chao2() for nonparametric richness.

Examples


coords <- data.frame(x = runif(150), y = runif(150))
species <- matrix(rbinom(150 * 60, 1, 0.15), nrow = 150)
area_fit <- extrapolateArea(species, coords, n_subareas = 8, progress = FALSE)
print(area_fit)



Extrapolate diversity beyond observed coverage

Description

Hill numbers at target sample coverages along a coverage-tracking accumulation, interpolated within the observed coverage and extrapolated beyond it (Chao et al. 2014).

Usage

extrapolateCoverage(x, target_coverage = c(0.9, 0.95, 0.99), q = 0)

Arguments

x

A spacc_coverage object from spaccCoverage() (richness, q = 0 only) or a spacc_hill_coverage object from spaccHillCoverage() (any of its orders).

target_coverage

Numeric vector of target coverage levels (0 to 1). Can exceed observed coverage for extrapolation. Default c(0.90, 0.95, 0.99).

q

Numeric. Diversity order: 0 (richness, default), or for a spacc_hill_coverage object one of its orders.

Details

A target at or below a seed's final coverage is read off that seed's spatial accumulation curve as in interpolateCoverage(): by linear interpolation in coverage between sites, and by rarefaction of the first site below that site's coverage. Above the final coverage, every seed has accumulated the same pooled sample, so the value is the coverage-based extrapolation of the pooled abundances (Chao et al. 2014): the sample size reaching the target coverage is found from the Chao-Jost coverage deficit, and the Hill number at that size approaches the Chao1 (q = 0), Chao et al. (2013) Shannon (q = 1) or unbiased Simpson (q = 2) asymptote; target_coverage = 1 gives the asymptote itself. Extrapolation is defined for integer q and for the individual-based coverage (coverage = "chao").

Value

An object of class spacc_coverage_ext containing:

richness

Matrix of interpolated/extrapolated Hill numbers of order q (n_seeds x n_targets)

target_coverage

Target coverage levels

q

Diversity order used

observed_coverage

Mean observed final coverage

observed_richness

Mean observed final Hill number of order q

References

Chao, A. & Jost, L. (2012). Coverage-based rarefaction and extrapolation: standardizing samples by completeness rather than size. Ecology, 93, 2533-2547.

Chao, A., Gotelli, N.J., Hsieh, T.C., et al. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84, 45-67.

See Also

spaccCoverage(), interpolateCoverage()

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rpois(50 * 30, 2), nrow = 50)
cov <- spaccCoverage(species, coords)
ext <- extrapolateCoverage(cov, target_coverage = c(0.95, 0.99))
print(ext)



Compute regional (gamma) diversity

Description

Compute Hill numbers for the pooled community across all sites.

Usage

gammaDiversity(x, q = c(0, 1, 2))

Arguments

x

A site-by-species matrix (abundance data).

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

Details

Gamma diversity represents regional (total) diversity across all sites. It is computed by pooling abundances across all sites and calculating Hill numbers on the combined community.

Value

A named numeric vector with gamma diversity for each q.

References

Jost, L. (2007). Partitioning diversity into independent alpha and beta components. Ecology, 88, 2427-2439. doi:10.1890/06-1736.1

See Also

alphaDiversity() for local diversity, diversityPartition() for full alpha-beta-gamma decomposition

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
gammaDiversity(species, q = c(0, 1, 2))


Estimate richness with the improved Chao1 (iChao1)

Description

Estimate total species richness using the improved Chao1 estimator (Chiu et al. 2014). Uses singletons through quadrupletons (f1–f4) to reduce bias for small samples.

Usage

iChao1(x)

Arguments

x

A site-by-species matrix (abundance data). Columns are pooled across sites.

Details

The improved Chao1 estimator adds a correction term using f3 and f4:

S_{iChao1} = S_{Chao1} + \frac{f_3}{4 f_4} \max\left(f_1 - \frac{f_2 f_3}{2 f_4}, 0\right)

When f_4 = 0, or the correction is 0, the estimator and its standard error are those of Chao1. Otherwise the standard error is the delta-method one over the frequency counts f_1, \ldots, f_4.

Value

An object of class spacc_estimate with components:

estimator

Name of the estimator ("iChao1")

estimate

Estimated total richness

se

Standard error of the estimate

lower

Lower 95 percent confidence bound

upper

Upper 95 percent confidence bound

S_obs

Observed species richness

details

List with f1, f2, f3, f4

References

Chiu, C.H., Wang, Y.T., Walther, B.A. & Chao, A. (2014). An improved nonparametric lower bound of species richness via a modified Good-Turing frequency formula. Biometrics, 70, 671-682.

See Also

chao1() for the standard estimator, iChao2() for incidence-based version

Examples

species <- matrix(rpois(50 * 30, 2), nrow = 50)
iChao1(species)


Estimate richness with the improved Chao2 (iChao2)

Description

Estimate total species richness from incidence data using the improved Chao2 estimator (Chiu et al. 2014). Uses uniques through quadruplicates (Q1–Q4) to reduce bias for small samples.

Usage

iChao2(x)

Arguments

x

A site-by-species matrix (presence/absence or abundance). Automatically binarized.

Details

The improved Chao2 estimator is the incidence-based analogue of iChao1:

S_{iChao2} = S_{Chao2} + \frac{t-3}{4t} \frac{Q_3}{Q_4} \max\left(Q_1 - \frac{t-3}{2(t-1)} \frac{Q_2 Q_3}{Q_4}, 0\right)

with t the number of sites.

When Q_4 = 0, or the correction is 0, the estimator and its standard error are those of Chao2. Otherwise the standard error is the delta-method one over the frequency counts Q_1, \ldots, Q_4.

Value

An object of class spacc_estimate with components:

estimator

Name of the estimator ("iChao2")

estimate

Estimated total richness

se

Standard error of the estimate

lower

Lower 95 percent confidence bound

upper

Upper 95 percent confidence bound

S_obs

Observed species richness

details

List with Q1, Q2, Q3, Q4, n_sites

References

Chiu, C.H., Wang, Y.T., Walther, B.A. & Chao, A. (2014). An improved nonparametric lower bound of species richness via a modified Good-Turing frequency formula. Biometrics, 70, 671-682.

See Also

chao2() for the standard estimator, iChao1() for abundance-based version

Examples

species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
iChao2(species)


Interpolate richness at target coverage levels

Description

Estimate species richness at specified coverage levels by interpolation.

Usage

interpolateCoverage(x, target = c(0.9, 0.95, 0.99))

Arguments

x

A spacc_coverage object.

target

Numeric vector of target coverage levels (0 to 1). Default c(0.90, 0.95, 0.99).

Details

Each seed's curve gives richness and coverage after 1, 2, ... sites. A target between the coverages of two consecutive sites is read off by linear interpolation in coverage. A target below the coverage of the seed's first site is reached inside that site, so the value is the coverage-based rarefaction of that site's individuals (Chao & Jost 2012): the expected richness of a random subsample of the size whose expected coverage equals the target, as in iNEXT::estimateD(base = "coverage"). A target above the seed's final coverage gives NA; extrapolateCoverage() goes beyond it.

Value

A data.frame with columns for each target coverage level, showing interpolated richness for each seed.

References

Chao, A. & Jost, L. (2012). Coverage-based rarefaction and extrapolation: standardizing samples by completeness rather than size. Ecology, 93, 2533-2547.


Estimate richness with the jackknife

Description

First- or second-order jackknife estimator of total species richness (Burnham & Overton 1978, 1979).

Usage

jackknife(x, order = 1L)

Arguments

x

A site-by-species matrix (presence/absence or abundance). Automatically binarized.

order

Integer. Jackknife order: 1 (default) or 2.

Details

First-order jackknife:

S_{jack1} = S_{obs} + Q_1 \frac{n-1}{n}

Second-order jackknife:

S_{jack2} = S_{obs} + \frac{Q_1(2n-3)}{n} - \frac{Q_2(n-2)^2}{n(n-1)}

Both are linear in the incidence frequency counts, S_{jack} = \sum_i a_i Q_i, with a_i = 1 except for the coefficients of Q_1 and Q_2 above. The standard error is that of Burnham & Overton (1978),

var(S_{jack}) = \sum_i a_i^2 Q_i - S_{jack},

and the interval is the estimate plus or minus 1.96 standard errors, with the lower bound no smaller than the observed richness.

Value

An object of class spacc_estimate.

References

Burnham, K.P. & Overton, W.S. (1978). Estimation of the size of a closed population when capture probabilities vary among animals. Biometrika, 65, 625-633.

Burnham, K.P. & Overton, W.S. (1979). Robust estimation of population size when capture probabilities vary among animals. Ecology, 60, 927-936.

See Also

chao2(), bootstrap_richness()

Examples

species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
jackknife(species, order = 1)
jackknife(species, order = 2)


Compute the exact (Mao Tau) expected accumulation curve

Description

Compute the expected species accumulation curve using sample-based rarefaction (Mao Tau estimator). This is analytically identical to the expected curve from random permutations.

Usage

mao_tau(x)

Arguments

x

A site-by-species matrix (presence/absence or abundance).

Details

The expected richness of h of the H sites is \tau(h) = \sum_i (1 - \alpha_{ih}), where \alpha_{ih} is the probability that none of the h sites holds species i. The standard deviation is the unconditional one of Colwell et al. (2004, Eq. 6),

\sigma^2(h) = \sum_i (1 - \alpha_{ih})^2 - \frac{\tau(h)^2}{\tilde{S}},

with \tilde{S} the Chao2 estimate of total richness (chao2()). It treats the H sites as a sample of a larger assemblage, so it does not fall to 0 at h = H, and vegan::specaccum(method = "exact", conditioned = FALSE, gamma = "chao") gives the same values. lower and upper are \tau(h) \pm 1.96 \sigma(h).

Value

A data.frame with columns: sites, expected, sd, lower, upper

References

Colwell, R.K., Mao, C.X. & Chang, J. (2004). Interpolating, extrapolating, and comparing incidence-based species accumulation curves. Ecology, 85, 2717-2727.


Plot spatial accumulation curves

Description

Create a ggplot2 visualization of species accumulation curves. For grouped spacc objects, curves are overlaid with different colors.

Usage

## S3 method for class 'spacc'
plot(
  x,
  ci = TRUE,
  ci_level = 0.95,
  ci_alpha = 0.3,
  show_seeds = FALSE,
  saturation = FALSE,
  saturation_level = 0.9,
  facet = FALSE,
  ...
)

Arguments

x

A spacc or summary.spacc object.

ci

Logical. Show confidence interval ribbon? Default TRUE.

ci_level

Numeric. Confidence level for interval. Default 0.95.

ci_alpha

Numeric. Transparency of CI ribbon. Default 0.3.

show_seeds

Logical. Show individual seed curves? Default FALSE. Only available for ungrouped objects.

saturation

Logical. Mark saturation point? Default FALSE. Only available for ungrouped objects.

saturation_level

Numeric. Proportion for saturation. Default 0.9.

facet

Logical. Use faceted panels for grouped objects? Default FALSE (overlay with colors). Ignored for ungrouped objects.

...

Additional arguments (ignored).

Value

A ggplot2 object.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords)
plot(sac)



Plot per-site accumulation metrics

Description

Create visualizations of per-site accumulation metrics.

Usage

## S3 method for class 'spacc_metrics'
plot(
  x,
  metric = NULL,
  type = c("heatmap", "points", "histogram"),
  point_size = 3,
  palette = "viridis",
  ...
)

Arguments

x

A spacc_metrics object from spaccMetrics().

metric

Character. Which metric to plot. Default is first metric.

type

Character. Plot type:

"heatmap"

Spatial heatmap colored by metric value

"points"

Simple point plot (same as heatmap but clearer name)

"histogram"

Distribution of metric values

point_size

Numeric. Size of points in heatmap. Default 3.

palette

Character. Color palette for heatmap. One of "magma" (A), "inferno" (B), "plasma" (C), "viridis" (D, default), "cividis" (E), "rocket" (F), "mako" (G), "turbo" (H). Single letters also accepted.

...

Additional arguments (unused).

Value

A ggplot2 object.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
metrics <- spaccMetrics(species, coords, metrics = c("slope_10", "auc"))
plot(metrics, metric = "slope_10", type = "heatmap")



Predict richness from an empirical accumulation curve

Description

Interpolate the mean empirical accumulation curve at arbitrary site counts using linear interpolation. Unlike the predict method for spacc_fit objects, this does not use a fitted model; it interpolates the observed curve directly.

Usage

## S3 method for class 'spacc'
predict(object, n = NULL, ci = TRUE, ci_level = 0.95, warn = TRUE, ...)

Arguments

object

A spacc object.

n

Numeric vector of site counts at which to interpolate. Defaults to 25%, 50%, and 100% of total sites.

ci

Logical. If TRUE (default), return a data frame with columns n, mean, lower, upper. If FALSE, return a named numeric vector.

ci_level

Confidence level for the interval (default 0.95).

warn

Logical. Warn when n values fall outside the observed range (default TRUE).

...

Ignored.

Value

A data frame (if ci = TRUE) or named numeric vector (if ci = FALSE). Out-of-range values return NA.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords, n_seeds = 10, progress = FALSE)
predict(sac, n = c(10, 25, 50))
predict(sac, n = c(10, 25), ci = FALSE)



Predict richness at a given area

Description

Predict richness at a given area

Usage

## S3 method for class 'spacc_area'
predict(
  object,
  area = NULL,
  interval = c("none", "bootstrap"),
  level = NULL,
  ...
)

Arguments

object

A spacc_area object.

area

Numeric vector of areas. Defaults to the observed T-S areas.

interval

"none" (default) or "bootstrap" for percentile bounds.

level

Confidence level. Defaults to the fit's level.

...

Unused.

Value

A numeric vector (point) or a data frame with area, fit, lower, upper.


Predict richness at a given sampling effort

Description

Predict richness at a given sampling effort

Usage

## S3 method for class 'spacc_fit'
predict(object, n = NULL, interval = c("none", "bootstrap"), level = NULL, ...)

Arguments

object

A spacc_fit object.

n

Integer vector of site counts. Defaults to the observed range.

interval

"none" (default) returns point predictions; "bootstrap" returns a data frame with percentile bounds from the stored bootstrap draws.

level

Confidence level for the interval. Defaults to the fit's level.

...

Unused.

Value

A numeric vector (point) or a data frame with n, fit, lower, upper (interval).


Rarefy Hill numbers by individuals

Description

Compute individual-based rarefaction curves for Hill numbers at any order q. This complements the sample-based accumulation in spacc().

Usage

rarefy(x, n_individuals = NULL, q = 0, n_boot = 100L)

Arguments

x

A site-by-species matrix with abundance data (not presence/absence).

n_individuals

Integer vector. Sample sizes to compute expected diversity for. Default NULL computes for all levels from 1 to total.

q

Numeric. Order of Hill number; any value ⁠>= 0⁠. Default 0 (species richness). q=1 gives rarefied Shannon diversity, q=2 gives rarefied Simpson diversity.

n_boot

Integer. Number of bootstrap replicates for the standard error. Default 100.

Details

The expected Hill number of a random subsample of n individuals drawn without replacement from the pooled sample (Chao et al. 2014). Each species' subsample count is hypergeometric, and

{}^qD(n) = \left(\sum_i E\left[(Y_i / n)^q\right]\right)^{1/(1-q)},

with the exponential of the expected Shannon entropy at q = 1. At q = 0 this is the Hurlbert (1971) formula. Sizes above the sample size are extrapolated towards the asymptotic estimators (Chao et al. 2014; integer q only).

The standard error follows the bootstrap of Chao et al. (2014), as in iNEXT::iNEXT(). Resampling the observed individuals can only lose species, so its replicates lie below the estimate. The replicates are drawn instead from an estimated assemblage that also holds the undetected species: their number is the Chao1 estimate, the probability mass they share is the estimated coverage deficit, and the relative abundances of the detected species are lowered to make room for it. The interval is the estimate plus or minus 1.96 standard errors. It describes the assemblage the sample was drawn from, so it has positive width at the full sample size too.

Value

An object of class spacc_rare containing:

n

Sample sizes

expected

Expected diversity (Hill number of order q)

sd

Bootstrap standard error

lower, upper

95 percent confidence bounds, expected plus or minus 1.96 sd

q

Order of diversity used

References

Hurlbert, S.H. (1971). The nonconcept of species diversity: a critique and alternative parameters. Ecology, 52, 577-586.

Chao, A., Gotelli, N.J., Hsieh, T.C., et al. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84, 45-67.

Examples


abundance_matrix <- matrix(rpois(50 * 30, 2), nrow = 50)
rare <- rarefy(abundance_matrix)
plot(rare)

# Shannon rarefaction
rare_q1 <- rarefy(abundance_matrix, q = 1)
plot(rare_q1)



Compute standardized effect sizes (SES) against null models

Description

Compute standardized effect sizes by comparing observed diversity metrics against a null distribution from randomized communities. Supports multiple null model algorithms and works with most spacc output classes.

Usage

ses(
  x,
  species,
  coords = NULL,
  metric = NULL,
  null_model = c("frequency", "richness", "both", "curveball", "torus", "spatial_swap",
    "shift_rotate"),
  n_perm = 999L,
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL
)

Arguments

x

A spacc output object. Supported classes: spacc, spacc_hill, spacc_phylo, spacc_func, spacc_beta, spacc_metrics, spacc_alpha, spacc_partition.

species

A site-by-species matrix (required). The species matrix used to produce x. Needed because spacc objects do not store the raw species matrix.

coords

Optional data.frame with columns x and y. Required if the original analysis used coordinates. If x contains stored coordinates, they will be used automatically.

metric

Character or NULL. For multi-metric objects (e.g., spacc_hill with multiple q), specify which metric to extract. If NULL, uses the first/default metric.

null_model

Character. Null model algorithm:

  • "frequency": Shuffle species columns independently (maintains column totals = species frequency)

  • "richness": Shuffle species rows independently (maintains row totals = site richness)

  • "both": Independent swap algorithm maintaining both row and column totals (Gotelli 2000)

  • "curveball": Curveball algorithm for efficient swap (Strona et al. 2014)

  • "torus": Toroidal shift preserving spatial autocorrelation. Shifts all coordinates by a random offset and reassigns species to shifted sites. Requires coords.

  • "spatial_swap": Independent swap restricted to spatially proximate site pairs. Preserves both marginals while respecting spatial structure. Requires coords.

  • "shift_rotate": Keeps the community and moves the sampling design: the user-supplied focal points of a method = "knn" analysis are rotated by a random angle and shifted by a random offset (Ridder et al. 2024). Requires coords.

n_perm

Integer. Number of permutations. Default 999.

parallel

Logical. Use parallel processing for the underlying analysis? Default TRUE.

n_cores

Integer. Number of cores. Default NULL (auto-detect).

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed for reproducibility.

Details

SES is computed as:

SES = \frac{observed - \bar{null}}{sd_{null}}

The two-tailed permutation p-value doubles the smaller of the two one-tailed p-values (b + 1)/(n_{perm} + 1), each counted with the observed value included among the permutations (Phipson & Smyth 2010, Sections 4 and 5):

p = \min\left(1, \frac{2 \cdot (\min(b_{\le}, b_{\ge}) + 1)}{n_{perm} + 1}\right)

where b_{\le} is the number of null values at or below the observed value and b_{\ge} the number at or above it. A null value equal to the observed one counts in both tails, so an observed value that every null value equals has p = 1. The smallest attainable p-value is 2 / (n_{perm} + 1). Permutations on which the analysis fails are dropped, and n_{perm} is then the number of valid ones (n_valid).

Under the null hypothesis the observed value is equally likely to take any of the n_{perm} + 1 ranks, and this p-value is exactly the probability of a rank at least as far into either tail, so a test at level \alpha rejects with probability at most \alpha. vegan::oecosimu() computes (2 \min(b_{\le}, b_{\ge}) + 1)/(n_{perm} + 1), which is smaller by 1/(n_{perm} + 1): with 99 permutations its smallest value is 0.01, which a null observation reaches with probability 0.02.

Null model algorithms:

For method = "knn" analyses the permutation nulls reuse the observed focal points, so observed and null curves share one design.

Value

An object of class spacc_ses containing:

observed

Numeric vector of observed metric values

null_mean

Mean of null distribution

null_sd

Standard deviation of null distribution

ses

Standardized effect size: (observed - null_mean) / null_sd

p_value

Two-tailed p-value

n_perm

Number of permutations

null_model

Null model algorithm used

metric

Metric name

input_class

Class of input object

References

Gotelli, N.J. (2000). Null model analysis of species co-occurrence patterns. Ecology, 81, 2606-2621.

Phipson, B. & Smyth, G.K. (2010). Permutation p-values should never be zero: calculating exact p-values when permutations are randomly drawn. Statistical Applications in Genetics and Molecular Biology, 9(1). doi:10.2202/1544-6115.1585

Strona, G., Nappo, D., Boccacci, F., Fattorini, S. & San-Miguel-Ayanz, J. (2014). A fast and unbiased procedure to randomize ecological binary matrices with fixed row and column totals. Nature Communications, 5, 4114.

Ridder, G., Hardy, O.J. & Ovaskainen, O. (2024). Generating spatially realistic environmental null models with the shift-&-rotate approach helps evaluate false positives in species distribution modelling. Methods in Ecology and Evolution, 15, 2331-2342. doi:10.1111/2041-210X.14443

See Also

spaccHill(), spaccBeta(), spaccMetrics()

Examples


coords <- data.frame(x = runif(20), y = runif(20))
species <- matrix(rbinom(20 * 15, 1, 0.3), nrow = 20)

sac <- spacc(species, coords, n_seeds = 10)
result <- ses(sac, species, n_perm = 19)
print(result)



Fit the sampling-effort species-area relationship (SESARS)

Description

Model the joint effect of sampling effort and area on species richness. Corrects for unequal survey intensity across sites, common in atlas data and citizen science datasets.

Usage

sesars(object, effort, model = c("power", "additive"), ...)

Arguments

object

An ungrouped spacc object.

effort

Numeric vector. Sampling effort per site (e.g., hours, visits, trap-nights), in the row order of the species matrix. Must have length equal to number of sites.

model

Character. SESARS model:

  • "power" (default): S = c * A^z * E^w (multiplicative power law)

  • "additive": S = c + z * log(A) + w * log(E)

...

Additional arguments passed to stats::lm().

Details

Standard SARs assume complete sampling within each area unit. SESARS incorporates sampling effort (E) alongside area (A), so that the area exponent is estimated net of unequal survey intensity. The power model is the log-log model \log S = \log c + z \log A + w \log E of Azovsky (2011, eq. 6); de la Sancha & Boyle (2019) compare it with the semi-log form fitted by model = "additive".

Every accumulation step of every seed is one observation: the richness of the first k sites of that site order, their number as the area proxy, and the summed effort of exactly those k sites. Orders that reach the same number of sites through differently surveyed sites separate the effort effect from the area effect. When effort varies little between sites, cumulative effort is nearly proportional to the number of sites, the two predictors are collinear and their exponents cannot be estimated independently (Azovsky 2011); cor(log(fit$data$area), log(fit$data$effort)) shows how close a dataset is to that case.

Value

An object of class spacc_sesars containing:

model

Model type

fit

Fitted model object

coef

Model coefficients

data

Data frame used for fitting, one row per seed and accumulation step: seed, area (number of sites accumulated), richness and effort (summed effort of those sites)

r_squared

Coefficient of determination of the fit

References

Azovsky, A.I. (2011). Species-area and species-sampling effort relationships: disentangling the effects. Ecography, 34, 18-30. doi:10.1111/j.1600-0587.2010.06288.x

de la Sancha, N.U. & Boyle, S.A. (2019). Predictive sampling effort and species-area relationship models for estimating richness in fragmented landscapes. PLOS ONE, 14, e0226529. doi:10.1371/journal.pone.0226529

See Also

extrapolate(), spacc()

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords)
effort <- rpois(50, 10) + 1
ses <- sesars(sac, effort, model = "power")
print(ses)



Fit the species-fragmented area relationship (SFAR)

Description

Separate the effect of habitat fragmentation from the effect of habitat area on species richness. Extends the power-law SAR with the metapopulation capacity of the fragmented landscape (Hanski et al. 2013).

Usage

sfar(object, patches, dispersal, scaling = c(1.5, 1), ...)

Arguments

object

An ungrouped spacc object.

patches

Factor or integer vector assigning each site to a habitat fragment (patch), in the row order of the species matrix. Must have length equal to the number of sites.

dispersal

Positive number, required. Average dispersal distance of the species, 1/\alpha of the dispersal kernel, in the units of the coordinates (kilometres for distance = "haversine"). It has no default because it is a property of the taxon: Hanski et al. (2013, p. 12717) take 300 m for forest birds from independent empirical data, and Hanski & Ovaskainen (2000, p. 758) take \alpha = 1 km^{-1} for the Glanville fritillary from mark-release-recapture studies. The capacity, and with it b, changes with this value.

scaling

Numeric vector of length 2. Exponents x and y that scale the effect of fragment area in the metapopulation capacity. The default c(1.5, 1) is the pair Hanski et al. (2013, pp. 12718-12719) use for birds and mammals; their simulations use c(2, 1).

...

Additional arguments passed to stats::lm().

Details

The SFAR multiplies the species number that the power-law SAR predicts for contiguous habitat by the fraction of species expected to persist at the given degree of fragmentation (Hanski et al. 2013, eqs. 1 and 2):

S = c A^z \exp(-b / \lambda), \qquad \log S = \log c + z \log A - b \lambda^{-1}

where A is the total habitat area and \lambda the metapopulation capacity of the landscape. A positive b means that fragmentation reduces richness beyond what the area alone predicts.

The metapopulation capacity is the leading eigenvalue of the matrix with elements m_{ii} = 0 and m_{ij} = A_i^x A_j^y f(d_{ij}), where A_i is the area of fragment i, d_{ij} the distance between the centroids of fragments i and j, and f(d) = \max(\exp(-\alpha d), 0.01) the dispersal kernel. It grows with the pooled area and falls as the habitat is split into smaller and more distant fragments.

Every accumulation step of every seed is one landscape: the first k sites of that site order. Its area is k (sites as the area proxy), its fragments are the patches those sites lie in, the area of a fragment is the number of accumulated sites in it and its centroid their mean position. A landscape of one fragment has \lambda = 0 under this definition, since the matrix has no off-diagonal element; such steps are left out of the fit.

Value

An object of class spacc_sfar containing:

fit

Fitted model object

coef

Coefficients: log_c (log intercept), z (area exponent), b (fragmentation coefficient)

data

Data frame used for fitting, one row per seed and accumulation step with at least two fragments: seed, area (number of sites accumulated), richness, n_fragments (fragments those sites lie in) and capacity (their metapopulation capacity)

n_patches

Number of habitat fragments

dispersal, scaling

Kernel parameters used

r_squared

Coefficient of determination of the fit

References

Hanski, I., Zurita, G.A., Bellocq, M.I. & Rybicki, J. (2013). Species-fragmented area relationship. Proceedings of the National Academy of Sciences, 110, 12715-12720. doi:10.1073/pnas.1311491110

Hanski, I. & Ovaskainen, O. (2000). The metapopulation capacity of a fragmented landscape. Nature, 404, 755-758. doi:10.1038/35008063

Rybicki, J. & Hanski, I. (2013). Species-area relationships and extinctions caused by habitat loss and fragmentation. Ecology Letters, 16, 27-38. doi:10.1111/ele.12065

See Also

extrapolate(), sesars()

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
sac <- spacc(species, coords)
patches <- kmeans(coords, centers = 5)$cluster
sfar_result <- sfar(sac, patches, dispersal = 0.1)
print(sfar_result)



Build spatial species accumulation curves

Description

Compute species accumulation curves using various spatial sampling methods with C++ backend for performance.

Usage

spacc(
  x,
  coords,
  n_seeds = 50L,
  method = c("knn", "kncn", "nn_walk", "random", "gaussian", "cone", "collector"),
  distance = c("euclidean", "haversine"),
  backend = c("auto", "exact", "kdtree"),
  support = NULL,
  include_halo = TRUE,
  sigma = NULL,
  cone_width = pi/4,
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  groups = NULL,
  time = NULL,
  w_space = 1,
  w_time = 1,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL,
  order = NULL
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species) with presence/absence (0/1) or abundance data. Can also be a data.frame. Missing values (NA) are an error: replace them by 0 where the species was looked for and not found, or drop the sites that were not surveyed.

coords

Site coordinates. Can be:

  • A data.frame with columns x and y

  • An sf object with point geometries (CRS is preserved)

  • A spacc_dist object from distances(). Its distances are then the ones every method uses, in place of distance (see Details).

n_seeds

Integer. Number of random focal points or starting sites for uncertainty quantification. Default 50.

method

Character. Accumulation method:

  • "knn": fixed-focus spatially constrained rarefaction

  • "kncn": k-Nearest Centroid Neighbor (visit closest to centroid)

  • "nn_walk": nearest-neighbour walk (move from the current site to the closest unvisited site)

  • "random": Random order (null model)

  • "gaussian": Probabilistic selection weighted by distance

  • "cone": Directional expansion: sites whose direction from the seed lies within cone_width of a random direction are added first, by increasing distance, then the remaining sites

  • "collector": Sites in data order (no randomization, single curve)

distance

Character. Distance method: "euclidean" for projected coordinates or "haversine" (great-circle distance in km) for longitude in x and latitude in y. With "haversine", the "cone" method reads directions as great-circle bearings.

backend

Character. Nearest-neighbor backend for nn_walk and kncn:

  • "auto" (default): Uses exact (brute-force) for <=500 sites, the index for >500 sites.

  • "exact": Always scan all unvisited sites (nn_walk from a precomputed distance matrix).

  • "kdtree": Always use the index, for Euclidean and haversine distances. For nn_walk it is a ball tree from which visited sites are removed; for kncn a heap of the unvisited sites' distances from earlier centroids, of which only those the centroid's movement could make the nearest are evaluated again. Faster for large datasets, no distance matrix needed. Both backends return the same orders. A supplied distance matrix (spacc_dist coordinates or the spatiotemporal composite built from time) is always used as given, so those inputs take the exact backend.

support

Optional. Spatial support for core/halo classification via areaOfEffect::aoe(). Can be:

  • "auto": Auto-detect countries and run per-country accumulation, returning a grouped spacc object with one curve per country

  • Country name or ISO code: "France", "FR", "FRA"

  • Vector of countries: c("France", "Germany")

  • An sf polygon object

  • An aoe_result object (pre-computed) When provided, seeds are sampled only from "core" sites (inside support), while accumulation can expand into "halo" sites (buffer zone).

include_halo

Logical. When support is provided, should halo sites be included in accumulation? Default TRUE (ecological boundary). Set to FALSE for political/hard boundary.

sigma

Numeric. Bandwidth for Gaussian method. Default auto-calculated.

cone_width

Numeric. Half-width in radians for cone method. Default pi/4.

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of threads the seeds are spread over. Default NULL uses detectCores() - 1.

progress

Logical. Show progress bar? Default TRUE.

groups

Optional. A factor, character, or integer vector of length ncol(x) assigning each species (column) to a group. When provided, separate accumulation curves are computed for each group using the same spatial site ordering, and a grouped spacc object is returned. Useful for comparing native vs alien species, families, or any categorical split. Default NULL (no grouping).

time

Optional. Numeric vector of length nrow(x) giving a temporal coordinate for each site. When provided, the space-time distance ⁠w_space * d_spatial + w_time * |t_i - t_j|⁠ between sites replaces the spatial distance for every method that orders sites by distance ("knn", "kncn", "nn_walk", "gaussian", "cone"), exactly as a spacc_dist input would (see Details). d_spatial is the supplied spacc_dist matrix, or the distance between the coordinates. "knn" then uses sites as focal points, since a continuous focal point has no time, and "cone" reads directions from the coordinates. "random" and "collector" never read a distance, so time is an error with them.

w_space

Numeric. Weight for spatial distance when time is provided. Default 1.

w_time

Numeric. Weight for temporal distance when time is provided. Default 1.

seed

Integer. Random seed for reproducibility. Default NULL.

focal_points

Optional data frame or sf point object with x and y coordinates. For method = "knn", each row is a fixed focal point and sites are accumulated by increasing distance from it. When supplied, n_seeds is set to the number of focal points. Default NULL samples continuous focal points uniformly from the spatial domain.

focal_domain

Optional sf or sfc polygon defining the domain from which continuous knn focal points are sampled. When omitted, the convex hull of the eligible site coordinates is used. For haversine distances, hull sampling uses a local equal-area projection. Supplying the study polygon preserves concavities, holes, and disconnected components in irregular sampling domains. Its coordinates must use the same coordinate reference system as coords.

order

Optional user-defined accumulation order(s). When supplied, method is ignored and sites are accumulated in the given sequence(s) (no distance computation or seed sampling). Can be:

  • A numeric vector of length nrow(x): a single ordering (one curve).

  • A list of such vectors, or a matrix with one ordering per row: each produces a curve, treated like seeds for uncertainty quantification. Each ordering must be a permutation of seq_len(nrow(x)). Cannot be combined with support or time. Default NULL.

Details

The canonical knn method follows Chiarucci et al. (2009): each curve uses one fixed focal point and accumulates sites by increasing distance from that point. The nn_walk method is a greedy traversal whose reference point moves to the most recently selected site. The two methods represent different spatial sampling models.

Every method is a rule for ordering the sites; the species data are then accumulated along those orders. The orders element of the result lets the same traversals be reused, for example through the order argument.

When coords is a spacc_dist object, or time is given, every method takes its distances from that matrix (the space-time distance under time), which only holds distances between sites:

Value

When groups = NULL, an object of class spacc containing:

curves

Matrix of cumulative species counts (n_seeds x n_sites)

orders

Matrix of 1-based site indices (n_seeds x n_sites): the order in which each curve visited the sites

coords

Original coordinates

n_seeds

Number of seeds used

method

Method used

n_species

Total species in dataset

focal_points

Continuous focal points used by method = "knn"

References

Arrhenius, O. (1921). Species and area. Journal of Ecology, 9, 95-99.

Scheiner, S.M. (2003). Six types of species-area curves. Global Ecology and Biogeography, 12, 441-447.

Chiarucci, A., Bacaro, G., Rocchini, D., Ricotta, C., Palmer, M.W. & Scheiner, S.M. (2009). Spatially constrained rarefaction: incorporating the autocorrelated structure of biological communities into sample-based rarefaction. Community Ecology, 10, 209-214.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)

# Basic usage
sac <- spacc(species, coords)
plot(sac)

# Different methods
sac_knn <- spacc(species, coords, method = "knn")
sac_rand <- spacc(species, coords, method = "random")
comp <- compare(sac_knn, sac_rand)



Accumulate beta diversity along a spatial order

Description

Analyze how beta diversity changes as sites are accumulated spatially. Partitions beta diversity into turnover (species replacement) and nestedness (species loss) components following Baselga (2010).

Usage

spaccBeta(
  x,
  coords,
  traits = NULL,
  tree = NULL,
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  index = c("sorensen", "jaccard"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  map = FALSE,
  map_k = NULL,
  focal_points = NULL,
  focal_domain = NULL,
  pool = NULL
)

Arguments

x

A site-by-species matrix (presence/absence or abundance).

coords

A data.frame with columns x and y, or a spacc_dist object.

traits

Optional species-by-traits matrix or data.frame of numeric traits (row names matching species). When supplied, functional beta diversity is computed.

tree

Optional rooted phylogenetic tree of class phylo with branch lengths, or an ultrametric matrix of pairwise phylogenetic distances (the tip distances of a dated tree). When supplied, phylogenetic beta diversity is computed. Supply at most one of traits or tree.

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

index

Character. Dissimilarity index: "sorensen" (default) or "jaccard".

distance

Character. Distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

map

Logical. If TRUE, run accumulation from every site as seed and store per-site beta values at map_k sites for spatial mapping. Enables as_sf() and plot(type = "map"). Default FALSE.

map_k

Integer. With map = TRUE, the step whose beta values are mapped: the beta diversity between the first map_k - 1 sites accumulated from each site and the map_k-th. Required with map = TRUE; at least 2.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

pool

Optional vector with one value per site (habitat, degradation level, region) grouping sites into pools. The partition is then also computed between pooled assemblages along the same orders.

Details

At each step of spatial accumulation, beta diversity is calculated between the accumulated species pool and the newly added site. This reveals how species composition changes as you expand spatially.

Interpretation:

The sum of turnover and nestedness equals total beta diversity.

The taxonomic partition is computed from three species counts: a shared by the accumulated pool and the new site, b found in the pool only and c in the site only. The functional and phylogenetic variants keep the formulas and measure a, b and c in other units.

Supplying tree computes phylogenetic beta diversity (Leprieur et al. 2012): a is the branch length the two assemblages share, b and c the branch length each holds alone. An assemblage holds every branch between one of its species and the root of the tree, as in betapart::phylo.beta.pair(). The Sorensen total is one minus the PhyloSor similarity of Bryant et al. (2008). Two assemblages with no branch in common score 1, and on a star tree with equal branch lengths the partition equals the taxonomic one.

Supplying traits computes functional beta diversity (Villeger et al. 2013): a is the volume of trait space the two assemblages share, b and c the volume each fills alone. The volume of an assemblage is the functional richness of spaccFunc(), the box spanned by the ranges of its species on each trait, so the shared volume is the product of the overlaps of the two ranges trait by trait. With a single trait this is the convex-hull partition of betapart::functional.beta.pair(); with several traits the box contains the convex hull. As for functional richness, an assemblage has no volume until it holds more species than there are traits and they differ on every trait; the partition is 0 at a step where neither the pool nor the site has any.

The taxonomic, functional, and phylogenetic variants all return a spacc_beta object whose beta_type field records which was computed. map = TRUE is supported for the taxonomic variant only.

With pool, sites are aggregated into pooled assemblages (a species is present in a pool if it occurs in any of its sites) and the partition is repeated between pools: each site order becomes the order in which its pools are first reached, and the distance between two pools is the mean distance between their sites. Partitions at the two resolutions can disagree, for example when degraded habitats are homogenised at the pool level while individual sites still differ (Jones et al. 2025). summary(x, resolution = "pooled") and plot(x, resolution = "pooled") or "both" show the pooled partition.

Value

An object of class spacc_beta containing:

beta_total

Matrix of total beta diversity (n_seeds x n_sites-1)

beta_turnover

Matrix of turnover component

beta_nestedness

Matrix of nestedness component

distance

Matrix of cumulative distances

pooled

With pool: the same four matrices for the pooled assemblages (n_seeds x n_pools-1), plus pool and n_pools; else NULL

orders

Matrix of 1-based site indices (n_seeds x n_sites): the order in which each seed visited the sites, as in spacc()

n_seeds, n_sites, method, index

Parameters used

distance_type

The distance argument used

References

Baselga, A. (2010). Partitioning the turnover and nestedness components of beta diversity. Global Ecology and Biogeography, 19, 134-143.

Bryant, J.A., Lamanna, C., Morlon, H., Kerkhoff, A.J., Enquist, B.J., et al. (2008). Microbes on mountainsides: contrasting elevational patterns of bacterial and plant diversity. Proceedings of the National Academy of Sciences of the United States of America, 105, 11505-11511.

Jones, F.A.M., Hardenbol, A.A., Hekkala, A.-M., et al. (2025). Partitioning beta diversity at two spatial resolutions reveals biotic homogenisation with habitat degradation. Diversity and Distributions, 31, e70080. doi:10.1111/ddi.70080

Leprieur, F., Albouy, C., De Bortoli, J., Cowman, P.F., Bellwood, D.R., et al. (2012). Quantifying phylogenetic beta diversity: distinguishing between "true" turnover of lineages and phylogenetic diversity gradients. PLoS ONE, 7, e42760. doi:10.1371/journal.pone.0042760

Villeger, S., Grenouillet, G. & Brosse, S. (2013). Decomposing functional beta-diversity reveals that low functional beta-diversity is driven by low functional turnover in European fish assemblages. Global Ecology and Biogeography, 22, 671-681.

See Also

betapart::beta.pair() for pairwise beta diversity

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)

beta <- spaccBeta(species, coords, n_seeds = 30)
plot(beta)

# Compare Sorensen vs Jaccard
beta_jac <- spaccBeta(species, coords, index = "jaccard")

# Functional beta diversity (pass a species-by-traits matrix)
traits <- matrix(rnorm(30 * 3), nrow = 30)
rownames(traits) <- colnames(species) <- paste0("sp", 1:30)
beta_func <- spaccBeta(species, coords, traits = traits)



Accumulate species with sample coverage tracking

Description

Compute spatial accumulation curves with sample coverage tracking. Allows standardization by completeness (coverage) rather than sample size, following Chao & Jost (2012) or the sample-based estimator of Chiu (2023).

Usage

spaccCoverage(
  x,
  coords,
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  coverage = c("chao", "chiu"),
  n_units = NULL,
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  map = FALSE,
  map_k = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix with abundance data.

coords

A data.frame with columns x and y, or a spacc_dist object.

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: canonical fixed-focus "knn" or "nn_walk". Default "knn".

distance

Character. Distance method: "euclidean" or "haversine".

coverage

Character. Coverage estimator to use: "chao" (default) for the individual-based Chao & Jost (2012) estimator using singletons/doubletons, or "chiu" for the sample-based Chiu (2023) estimator using incidence frequency counts (Q1/Q2) and unique-species abundance (G1). The Chiu estimator is recommended for spatially aggregated data where sampling units are plots/sites rather than independent individuals.

n_units

Total number of sampling units in the study region, when the sites are drawn without replacement from a finite set of units (atlas cells, a plot network). Requires coverage = "chiu". NULL (default) or Inf assumes sampling with replacement. See Details.

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

map

Logical. If TRUE, run accumulation from every site as seed and store per-site coverage, richness and individuals at map_k sites for spatial mapping. Enables as_sf() and plot(type = "map"). Default FALSE.

map_k

Integer. With map = TRUE, the number of sites accumulated from each site before its value is read: the map shows the coverage, richness and number of individuals of each site's neighbourhood of map_k sites. Required with map = TRUE; map_k = 1 is the site alone. The last step pools every site, so it is the same for all sites.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

Sample coverage estimates the proportion of the total community abundance represented by observed species. It provides a measure of sampling completeness that is independent of sample size.

The Chao-Jost (2012) estimator counts singletons (f1) and doubletons (f2) in the cumulative abundance vector of n individuals,

C = 1 - \frac{f_1}{n} \frac{(n-1) f_1}{(n-1) f_1 + 2 f_2},

with the second factor \frac{(n-1)(f_1-1)}{(n-1)(f_1-1) + 2} when there are no doubletons, as in iNEXT; one individual gives 0. It assumes individuals are sampled independently, which may not hold for plot-based spatial data.

The Chiu (2023) estimator uses incidence frequency counts instead: Q1 (species in exactly 1 site), Q2 (species in exactly 2 sites), and G1 (total abundance of Q1 species). It gives near-unbiased coverage estimates when organisms are spatially aggregated across sampling units. It writes the abundance of undetected species as the Chao2 estimate of their number, \frac{t-1}{t} \frac{Q_1^2}{2 Q_2} after t sites, times the mean abundance of a unique species, G_1 / Q_1.

With n_units = T, the t sites are a fraction w = t / T of a finite set of units drawn without replacement, and the number of undetected species is the MoRE term of chao2(x, n_units = ) (Chiu 2023, Methods in Ecology and Evolution, Eq. 5),

\frac{t-1}{t} \frac{(1-w) Q_1^2}{Q_2 + w (Q_1 - Q_2)^+},

so richness and coverage of the same sample rest on one estimate of the undetected species. It vanishes at w = 1: the coverage reaches 1 once the accumulation has visited every unit. On simulated grids its error is lower than that of the with-replacement form from w = 0.5 on, and several-fold lower near a census; it is about equal at w = 0.3 and larger at w = 0.1 on a sparse grid (Standardising by sample coverage).

Coverage-based rarefaction allows fair comparison of diversity across communities with different abundances by standardizing to equal completeness rather than equal sample size.

Value

An object of class spacc_coverage containing:

richness

Matrix of species richness (n_seeds x n_sites)

individuals

Matrix of individual counts

coverage

Matrix of coverage estimates

pooled

Species abundances pooled over all sites

first_site

Species abundances of each seed's first site (n_seeds x n_species)

coverage_type

Coverage estimator used ("chao" or "chiu")

n_units

Number of units in the finite population, or NULL

coords, n_seeds, n_sites, method

Parameters used

References

Chao, A. & Jost, L. (2012). Coverage-based rarefaction and extrapolation: standardizing samples by completeness rather than size. Ecology, 93, 2533-2547.

Chiu, C.-H. (2023). A species richness estimator for sample-based incidence data sampled without replacement. Methods in Ecology and Evolution, 14, 2482-2493. doi:10.1111/2041-210X.14146

Chiu, C.-H. (2023). A sample-based estimator for sample coverage. Ecology, 104, e4099.

See Also

iNEXT::iNEXT() for coverage-based rarefaction without spatial structure

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rpois(50 * 30, 2), nrow = 50)

cov <- spaccCoverage(species, coords)
plot(cov)

# Sample-based coverage (recommended for spatial data)
cov_chiu <- spaccCoverage(species, coords, coverage = "chiu")

# The 50 sites are 80% of a 62-cell grid
cov_grid <- spaccCoverage(species, coords, coverage = "chiu", n_units = 62)

# Interpolate richness at 90% and 95% coverage
interp <- interpolateCoverage(cov, target = c(0.90, 0.95))



Accumulate a custom diversity metric along a spatial order

Description

Accumulate any user-supplied diversity index along a spatial ordering of sites. At each accumulation step the cumulative community is passed to fun, which returns a single number. This is the general escape hatch behind the built-in metric functions: use it for indices that spacc does not implement directly.

Usage

spaccDiversity(
  x,
  coords,
  fun,
  ...,
  method = c("knn", "kncn", "nn_walk", "random", "collector"),
  incidence = FALSE,
  n_seeds = 50L,
  distance = c("euclidean", "haversine"),
  progress = TRUE,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species), abundance or presence/absence.

coords

A data.frame with columns x and y, or a spacc_dist object.

fun

A function applied to the cumulative community at each step. It receives a named numeric vector of length ncol(x) (cumulative summed abundances, or 0/1 incidences when incidence = TRUE) plus any arguments passed through ..., and must return a single numeric value.

...

Additional arguments passed to fun.

method

Character. Spatial ordering of sites: "knn" (default), "kncn", "nn_walk", "random", or "collector".

incidence

Logical. If TRUE, fun receives 0/1 incidences instead of summed abundances. Default FALSE.

n_seeds

Integer. Number of random starting points / orderings. Ignored for "collector" (a single data-order curve). Default 50.

distance

Character. "euclidean" or "haversine".

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed for reproducibility.

focal_points

Optional focal points passed to the canonical knn ordering. See spacc().

focal_domain

Optional polygonal focal domain passed to spacc().

Details

The site ordering reuses the same spatial traversals as the built-in methods (fixed-focus, nearest-neighbour walk, nearest-centroid, random, or data order), then evaluates fun on the accumulating community. Because the index is an arbitrary R function, this trades the speed of the compiled metrics for full flexibility.

Value

An object of class spacc_diversity that inherits from spacc, so the standard summary(), plot(), as.data.frame() and predict() methods apply. curves is an ⁠n_seeds x n_sites⁠ matrix of the metric along the accumulation.

See Also

spaccHill(), spaccPhylo(), spaccFunc() for built-in metrics.

Examples


coords <- data.frame(x = runif(40), y = runif(40))
species <- matrix(rpois(40 * 20, 2), nrow = 40)

# Shannon entropy along the accumulation
shannon <- function(comm) {
  p <- comm[comm > 0] / sum(comm)
  -sum(p * log(p))
}
div <- spaccDiversity(species, coords, shannon, n_seeds = 20)
plot(div)



Accumulate endemic species along a spatial order

Description

Compute the number of endemic species (species found only within the accumulated area) as sites are added spatially. Complements the standard SAC by tracking species unique to each spatial extent.

Usage

spaccEndemism(
  x,
  coords,
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  map = FALSE,
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix (presence/absence or abundance).

coords

A data.frame with columns x and y, or a spacc_dist object.

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method. Default "knn".

distance

Character. Distance method: "euclidean" or "haversine".

map

Logical. If TRUE, compute the endemism richness of each site (Kier et al. 2009; see Details) and store it in a site_values data.frame, enabling plot(type = "map") and as_sf(). Default FALSE.

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

At each accumulation step k, an endemic species is one that is present in the accumulated sites (1..k) but absent from all remaining unvisited sites (k+1..n). This tracks how many species are unique to the area sampled so far.

The endemism curve typically starts low (few endemics at small areas), increases as the region grows, and eventually equals total richness when all sites are included.

The per-site map (map = TRUE) uses the endemism richness of Kier et al. (2009) with the site as mapping unit. Each species carries one range equivalent, spread equally over the sites it occupies, and the endemism richness of a site is the sum of the fractions it holds:

ER_i = \sum_{s \in i} \frac{1}{t_s}

where t_s is the number of sites species s occupies. A species found at one site only contributes 1 to that site; a species found at ten sites contributes 0.1 to each. The values sum to the total number of species over all sites, so endemism_prop, the endemism richness divided by total richness, is the share of the region's species a site accounts for. The map does not depend on the accumulation method.

Value

An object of class spacc_endemism containing:

richness

Matrix of cumulative richness (n_seeds x n_sites)

endemism

Matrix of endemic species count (n_seeds x n_sites)

site_values

Per-site data.frame (if map = TRUE) with site_id, x, y, endemism (endemism richness in range equivalents) and endemism_prop (its share of the total over all sites)

coords, n_seeds, n_sites, method

Parameters used

References

Kier, G., Kreft, H., Lee, T.M., et al. (2009). A global assessment of endemism and species richness across island and mainland regions. Proceedings of the National Academy of Sciences, 106, 9322-9327.

May, F., Gerstner, K., McGlinn, D.J., et al. (2018). mobsim: an R package for the simulation and measurement of biodiversity across spatial scales. Methods in Ecology and Evolution, 9, 1401-1408.

See Also

spacc(), spaccHill()

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)

end <- spaccEndemism(species, coords, n_seeds = 30)
plot(end)



Accumulate functional diversity along a spatial order

Description

Compute spatial accumulation of functional diversity metrics based on traits.

Usage

spaccFunc(
  x,
  coords,
  traits,
  metric = c("fdis", "fric"),
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  map = FALSE,
  map_k = NULL,
  focal_points = NULL,
  focal_domain = NULL,
  axis_length_k = NULL,
  itv = FALSE
)

Arguments

x

A site-by-species matrix (abundance data recommended).

coords

A data.frame with columns x and y, or a spacc_dist object.

traits

A species-by-traits matrix. Row names should match species (columns of x).

metric

Character vector. Metrics to compute:

  • "fdis": Functional Dispersion (mean distance to centroid)

  • "fric": Functional Richness (volume of the box spanned by the trait ranges)

  • "rao": Rao's quadratic entropy (abundance-weighted mean pairwise Euclidean trait distance)

  • "K": aggregated functional diversity (Wojcik et al. 2024), reported with its four facets as k_richness, k_biomass_evenness, k_trait_evenness, k_dispersion and K

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

distance

Character. Site distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

map

Logical. If TRUE, run accumulation from every site as seed and store per-site values at map_k sites for spatial mapping. Enables as_sf() and plot(type = "map"). Default FALSE.

map_k

Integer. With map = TRUE, the number of sites accumulated from each site before its value is read: the map shows each metric for the site's neighbourhood of map_k sites. Required with map = TRUE; map_k = 1 is the site alone. The last step pools every site, so it is the same for all sites.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

axis_length_k

Numeric vector, one value per trait. Length of each trait axis for the richness facet of "K". Default NULL uses the range of each trait over all species in traits.

itv

Logical. Use intraspecific trait variability: traits is then a long data frame with one row per individual or population, a species column, an optional site column (matched like the sites of spaccNetwork()) and numeric trait columns. Default FALSE.

Details

Functional diversity metrics quantify trait space occupation:

Intraspecific trait variability (itv = TRUE; Palacio et al. 2025). Each trait row is a unit of the community in place of a species: at each step the metrics are evaluated on the rows describing the accumulated sites, each weighted by its species' abundance at its site, shared equally among the rows describing that species there. Rows without a site (no site column, or NA) stand for the species at every site where it has no site-specific rows, so one row per species reproduces the species-mean curves. A widespread species whose traits change along a gradient then adds trait range as the accumulation reaches new parts of the gradient, which its mean trait value hides.

Value

An object of class spacc_func containing:

curves

Named list of matrices, one per metric (n_seeds x n_sites)

metric

Metrics computed

coords, n_seeds, n_sites, method

Parameters used

References

Laliberté, E. & Legendre, P. (2010). A distance-based framework for measuring functional diversity from multiple traits. Ecology, 91, 299-305.

Palacio, F.X., Ottaviani, G., Mammola, S., Graco-Roza, C., de Bello, F. & Carmona, C.P. (2025). Integrating intraspecific trait variability in functional diversity: an overview of methods and a guide for ecologists. Ecological Monographs, 95, e70024. doi:10.1002/ecm.70024

Wojcik, L.A., Gaedke, U., van Velzen, E. & Klauschies, T. (2024). Measuring overall functional diversity by aggregating its multiple facets: functional richness, biomass evenness, trait evenness and dispersion. Methods in Ecology and Evolution, 16, 215-227. doi:10.1111/2041-210X.14470

See Also

FD::dbFD() for comprehensive functional diversity analysis

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rpois(50 * 20, 2), nrow = 50)

# Trait matrix (species x traits)
traits <- matrix(rnorm(20 * 3), nrow = 20)
rownames(traits) <- paste0("sp", 1:20)
colnames(species) <- rownames(traits)

func <- spaccFunc(species, coords, traits, metric = c("fdis", "fric"))
plot(func)



Accumulate Hill numbers along a spatial order

Description

Compute spatial species accumulation curves using Hill numbers (effective number of species) instead of raw richness. Hill numbers unify diversity measures: q=0 is richness, q=1 is exponential Shannon, q=2 is inverse Simpson.

Usage

spaccHill(
  x,
  coords,
  q = c(0, 1, 2),
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  map = FALSE,
  map_k = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species) with presence/absence (0/1) or abundance data.

coords

A data.frame with columns x and y containing site coordinates, or a spacc_dist object from distances().

q

Numeric vector. Orders of diversity to compute. Default c(0, 1, 2).

  • q = 0: Species richness

  • q = 1: Exponential of Shannon entropy (effective common species)

  • q = 2: Inverse Simpson (effective dominant species)

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

distance

Character. Distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores. Default NULL uses detectCores() - 1.

progress

Logical. Show progress bar? Default TRUE.

seed

Integer. Random seed for reproducibility.

map

Logical. If TRUE, run accumulation from every site as seed and store per-site Hill numbers at map_k sites for spatial mapping. Enables as_sf() and plot(type = "map"). Default FALSE.

map_k

Integer. With map = TRUE, the number of sites accumulated from each site before its value is read: the map shows the Hill numbers of each site's neighbourhood of map_k sites. Required with map = TRUE; map_k = 1 is the site alone. The last step pools every site, so it is the same for all sites.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

Hill numbers (Chao et al. 2014) provide a unified framework for diversity measurement. Unlike raw richness (q=0), higher-order Hill numbers (q=1, q=2) down-weight rare species, providing different perspectives on diversity.

The spatial accumulation of Hill numbers can reveal scale-dependent diversity patterns missed by richness alone.

Value

An object of class spacc_hill containing:

curves

Named list of matrices, one per q value (n_seeds x n_sites)

q

Vector of q values used

coords

Original coordinates

n_seeds

Number of seeds

n_sites

Number of sites

n_species

Total species

method

Method used

References

Chao, A., Gotelli, N.J., Hsieh, T.C., Sander, E.L., Ma, K.H., Colwell, R.K. & Ellison, A.M. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84, 45-67.

See Also

spacc() for richness-only accumulation, iNEXT::iNEXT() for non-spatial Hill number rarefaction

Examples


# Compare diversity at different orders
coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rpois(50 * 30, 2), nrow = 50)

hill <- spaccHill(species, coords, q = c(0, 1, 2))
plot(hill)

# Extract summary at final site
summary(hill)



Partition accumulated Hill numbers into alpha, beta and gamma

Description

Compute multisite beta diversity as gamma/alpha decomposition of Hill numbers along the spatial accumulation curve (Jost 2007 framework).

Usage

spaccHillBeta(
  x,
  coords,
  q = c(0, 1, 2),
  n_seeds = 50L,
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  method = c("knn", "nn_walk"),
  focal_points = NULL,
  focal_domain = NULL,
  standardize = c("none", "coverage"),
  coverage = NULL
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species).

coords

A data.frame with columns x and y, or a spacc_dist object.

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

n_seeds

Integer. Number of random starting points. Default 50.

distance

Character. "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores. Default NULL.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

method

Character. Accumulation method: "knn" or "nn_walk".

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

standardize

Character. "none" (default) decomposes the observed samples; "coverage" standardises gamma and alpha to a common sample coverage at every step (iNEXT.beta3D, Chao et al. 2023). Needs integer abundances.

coverage

Numeric in (0, 1]. Fixed coverage for standardize = "coverage", the same at every step. NULL (default) uses, at each step, the lower of the observed coverages of the pooled and joint samples.

Details

At each accumulation step k, the function computes:

Beta = 1 means all sites are identical; beta = k means all sites are completely different. This provides the Hill-number analogue of the Baselga-based spaccBeta().

Value

An object of class spacc_hill_beta containing:

gamma

Named list of n_seeds x n_sites matrices (one per q)

alpha

Named list of n_seeds x n_sites matrices (one per q)

beta

Named list of n_seeds x n_sites matrices (one per q)

dissimilarity

With standardize = "coverage": list of the four dissimilarities 1-CqN, 1-UqN, 1-VqN, 1-SqN, each a named list of n_seeds x n_sites matrices (one per q); NULL otherwise

coverage

With standardize = "coverage": n_seeds x n_sites matrix of the coverage used at each step

q

Vector of q values

coords

Original coordinates

n_seeds, n_sites, n_species

Dimensions

Coverage standardisation

Observed beta depends on sampling completeness: gamma and alpha approach their asymptotes at different rates, so the ratio moves along the curve even where composition does not change. With standardize = "coverage", gamma is the Hill number of the pooled sample and alpha the Hill number of the joint sample (every species-by-site cell treated as a unit) divided by k (Chiu et al. 2014), both rarefied or extrapolated to the same sample coverage C with the estimators of Chao et al. (2014); beta is their ratio (Chao et al. 2023). By default C is, at each step, the lower of the two observed coverages, so both values come from the observed samples or their rarefaction. A fixed coverage makes the curve comparable across steps and datasets, at the cost of extrapolation where a step's sample is less complete; for q = 0, Chao et al. (2023) advise against extrapolating beyond the coverage of twice the sample size.

The standardised beta is transformed to four dissimilarities between 0 and 1 (Chao et al. 2023): 1-CqN (Sorensen-type, the classic Sorensen index at q = 0), 1-UqN (Jaccard-type), 1-VqN and 1-SqN. They are NA at the first step, where there is one site.

References

Jost, L. (2007). Partitioning diversity into independent alpha and beta components. Ecology, 88, 2427-2439.

Chiu, C.-H., Jost, L. & Chao, A. (2014). Phylogenetic beta diversity, similarity, and differentiation measures based on Hill numbers. Ecological Monographs, 84, 21-44.

Chao, A., Gotelli, N.J., Hsieh, T.C., et al. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84, 45-67.

Chao, A., Thorn, S., Chiu, C.-H., et al. (2023). Rarefaction and extrapolation with beta diversity under a framework of Hill numbers: the iNEXT.beta3D standardization. Ecological Monographs, 93, e1588. doi:10.1002/ecm.1588

See Also

spaccBeta() for P/A-based Baselga partitioning, spaccHill() for Hill accumulation without beta decomposition

Examples


coords <- data.frame(x = runif(40), y = runif(40))
species <- matrix(rpois(40 * 20, 2), nrow = 40)

hb <- spaccHillBeta(species, coords, n_seeds = 10, progress = FALSE)
plot(hb)



Accumulate Hill numbers at standardized coverage

Description

Compute spatial accumulation of Hill numbers alongside sample coverage, enabling standardized comparison at equal completeness levels (iNEXT-style analysis applied spatially).

Usage

spaccHillCoverage(
  x,
  coords,
  q = c(0, 1, 2),
  target_coverage = NULL,
  n_seeds = 50L,
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  method = c("knn", "nn_walk"),
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species) with abundance data.

coords

A data.frame with columns x and y containing site coordinates, or a spacc_dist object from distances().

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

target_coverage

Numeric vector. Target coverage levels for standardization. Default NULL (no standardization). Values in (0, 1).

n_seeds

Integer. Number of random starting points. Default 50.

distance

Character. Distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores. Default NULL uses all minus one.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed for reproducibility.

method

Character. Accumulation method: "knn" or "nn_walk".

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

Combines spatial kNN accumulation with simultaneous Hill number and coverage computation. At each accumulation step, both the Chao-Jost sample coverage and Hill numbers for all requested orders are calculated.

When target_coverage is specified, Hill numbers are interpolated at those coverage levels as in interpolateCoverage(): linearly in coverage between consecutive sites, and by rarefaction of the first site's individuals below that site's coverage. This enables fair comparison between sites with different sampling completeness.

Value

An object of class spacc_hill_coverage containing:

hills

Named list of n_seeds x n_sites matrices (one per q)

coverage

n_seeds x n_sites matrix of Chao-Jost coverage

pooled

Species abundances pooled over all sites

standardized

List of per-q values interpolated at target coverage, or NULL if target_coverage is NULL

q

Vector of q values

target_coverage

Target coverage levels used

coords

Original coordinates

n_seeds

Number of seeds

n_sites

Number of sites

n_species

Total species

References

Chao, A. & Jost, L. (2012). Coverage-based rarefaction and extrapolation: standardizing samples by completeness rather than size. Ecology, 93, 2533-2547.

Chao, A., Gotelli, N.J., Hsieh, T.C., Sander, E.L., Ma, K.H., Colwell, R.K. & Ellison, A.M. (2014). Rarefaction and extrapolation with Hill numbers. Ecological Monographs, 84, 45-67.

See Also

spaccHill() for Hill accumulation without coverage, spaccCoverage() for coverage accumulation without Hill numbers

Examples


coords <- data.frame(x = runif(40), y = runif(40))
species <- matrix(rpois(40 * 20, 2), nrow = 40)

hc <- spaccHillCoverage(species, coords, n_seeds = 10, progress = FALSE)
plot(hc)

# Standardize at 90% coverage
hc2 <- spaccHillCoverage(species, coords, target_coverage = 0.9,
                          n_seeds = 10, progress = FALSE)
summary(hc2)



Compute accumulation metrics for each site as starting point

Description

Compute spatial accumulation metrics for each site as a starting point. Useful for identifying sites with high or low accumulation rates, visualizing spatial patterns in diversity, and understanding edge effects.

Usage

spaccMetrics(
  x,
  coords,
  metrics = c("slope_10", "half_richness", "auc"),
  method = c("knn", "kncn", "nn_walk", "random"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE
)

Arguments

x

A site-by-species matrix (rows = sites, cols = species).

coords

A data.frame with columns x and y containing site coordinates, or a spacc_dist object from distances().

metrics

Character vector. Metrics to compute. Options include: "slope_10" (initial slope, first 10% of sites), "slope_25" (initial slope, first 25% of sites), "half_richness" (sites to reach 50% of total species), "richness_50pct" (alias for half_richness), "richness_75pct" (sites to reach 75% of species), "richness_90pct" (sites to reach 90% of species), "auc" (area under accumulation curve), "final_richness" (total species starting from this site).

method

Character. Accumulation method: "knn", "kncn", "nn_walk", or "random". Default "knn".

distance

Character. Distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores for parallel processing.

progress

Logical. Show progress bar? Default TRUE.

Details

This function runs a spatial accumulation curve starting from each site individually, then extracts summary metrics from each curve. This allows you to identify:

The metrics can be plotted as a heatmap using plot(result, type = "heatmap"), which requires the ggplot2 package. For more sophisticated spatial visualization with study area boundaries, see the areaOfEffect package.

Value

An object of class spacc_metrics containing:

metrics

Data frame with one row per site and columns for each metric

coords

Original coordinates

metric_names

Names of computed metrics

n_sites

Number of sites

n_species

Total species count

References

Soberon, J.M. & Llorente, J.B. (1993). The use of species accumulation functions for the prediction of species richness. Conservation Biology, 7, 480-488.

See Also

spacc() for standard accumulation curves

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
metrics <- spaccMetrics(species, coords,
                        metrics = c("slope_10", "auc"))
metrics$metrics$slope_10



Accumulate interaction diversity along a spatial order

Description

Accumulate an interaction network over space: interaction richness and interaction Hill numbers, sample coverage, the richness of the two interacting levels (for example plants and pollinators) and connectance, all along the same site orders.

Usage

spaccNetwork(
  interactions,
  coords,
  q = c(0, 1, 2),
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

interactions

A data frame of observed interactions with columns site, lower, upper and optionally count (interaction frequency, default 1 per row). lower and upper name the species of the two levels; an interaction is a lower-upper pair.

coords

A data frame with columns x and y, one row per site. Sites in interactions are matched to coords$site if present, otherwise to the row names of coords, otherwise taken as row numbers.

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

distance

Character. "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

Each unique lower-upper pair is a unit of diversity and its frequency its abundance, so the interaction Hill number of order q is the ordinary Hill number of the interaction frequencies of the accumulated sites, the effective number of equally frequent interactions, and the sample coverage is the Chao & Jost (2012) coverage of those frequencies (Chiu et al. 2023). The species curves of the two levels use each species' summed interaction frequency. Connectance is the realised share of the possible interactions between the species detected so far.

Value

An object of class spacc_network containing:

interaction, lower, upper

Named lists (one per q) of n_seeds x n_sites matrices: Hill numbers of the interaction frequencies and of the summed frequencies of each level's species

coverage

List with the n_seeds x n_sites sample coverage matrices of interaction, lower and upper

connectance

n_seeds x n_sites matrix of interaction richness divided by the product of the two species richnesses

q, coords, n_seeds, n_sites, n_interactions, n_lower, n_upper, method, orders

Parameters, dimensions and site orders

References

Chiu, C.-H., Chao, A., Vogel, S., Kriegel, P. & Thorn, S. (2023). Quantifying and estimating ecological network diversity based on incomplete sampling data. Philosophical Transactions of the Royal Society B, 378, 20220183. doi:10.1098/rstb.2022.0183

See Also

spaccHillCoverage() for the same quantities on species

Examples


set.seed(1)
coords <- data.frame(x = runif(30), y = runif(30))
interactions <- data.frame(
  site = sample(30, 400, replace = TRUE),
  lower = paste0("plant", sample(12, 400, replace = TRUE)),
  upper = paste0("bee", sample(20, 400, replace = TRUE))
)
net <- spaccNetwork(interactions, coords, n_seeds = 10)
net
plot(net)



Accumulate phylogenetic diversity along a spatial order

Description

Compute spatial accumulation of phylogenetic diversity metrics (MPD, MNTD, PD).

Usage

spaccPhylo(
  x,
  coords,
  tree,
  metric = c("mpd", "mntd"),
  rho = 0,
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  map = FALSE,
  map_k = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix.

coords

A data.frame with columns x and y, or a spacc_dist object.

tree

A phylogenetic tree of class phylo (from ape package), or a pairwise phylogenetic distance matrix.

metric

Character vector. Metrics to compute:

  • "mpd": Mean Pairwise Distance

  • "mntd": Mean Nearest Taxon Distance

  • "pd": Faith's Phylogenetic Diversity (requires tree, not distance matrix)

  • "evoheritage": EvoHeritage (Rosindell et al. 2024), PD with attrition of evolutionary heritage at rate rho (requires tree)

  • "rao": Rao's quadratic entropy (abundance-weighted mean pairwise phylogenetic distance). Pass abundance data for weighting; with presence/absence it reduces to the equal-weight form.

rho

Non-negative numeric vector. Attrition rate(s) for "evoheritage", per unit of branch length. rho = 0 gives Faith's PD. Several values give one curve each, named ⁠evoheritage_rho<value>⁠.

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

distance

Character. Site distance method: "euclidean" or "haversine".

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

map

Logical. If TRUE, run accumulation from every site as seed and store per-site values at map_k sites for spatial mapping. Enables as_sf() and plot(type = "map"). Default FALSE.

map_k

Integer. With map = TRUE, the number of sites accumulated from each site before its value is read: the map shows each metric for the site's neighbourhood of map_k sites. Required with map = TRUE; map_k = 1 is the site alone. The last step pools every site, so it is the same for all sites.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

Phylogenetic diversity metrics incorporate evolutionary relationships:

Tree-based metrics match the columns of x to tree$tip.label by name; the tree may contain species absent from x.

Value

An object of class spacc_phylo containing:

curves

Named list of matrices, one per metric (n_seeds x n_sites)

metric

Metrics computed

tree

The tree or distance matrix used

coords, n_seeds, n_sites, method

Parameters used

References

Faith, D.P. (1992). Conservation evaluation and phylogenetic diversity. Biological Conservation, 61, 1-10.

Rosindell, J., Manson, K., Gumbs, R., Pearse, W.D. & Steel, M. (2024). Phylogenetic biodiversity metrics should account for both accumulation and attrition of evolutionary heritage. Systematic Biology, 73, 158-182. doi:10.1093/sysbio/syad072

Webb, C.O. (2000). Exploring the phylogenetic structure of ecological communities: an example for rain forest trees. American Naturalist, 156, 145-155.

See Also

picante::mpd(), picante::mntd(), picante::pd()

Examples


if (requireNamespace("ape", quietly = TRUE)) {
  # Create random tree
  tree <- ape::rtree(30)

  coords <- data.frame(x = runif(50), y = runif(50))
  species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
  colnames(species) <- tree$tip.label

  phylo <- spaccPhylo(species, coords, tree, metric = c("mpd", "mntd"))
  plot(phylo)
}



Accumulate phylogenetic or functional redundancy along a spatial order

Description

Track how much of the taxonomic diversity added along the spatial accumulation is new phylogenetic or functional diversity, as the ratio of the taxonomic Hill number to the phylogenetic or functional Hill number of the accumulated community.

Usage

spaccRedundancy(
  x,
  coords,
  tree = NULL,
  traits = NULL,
  q = c(0, 1, 2),
  n_seeds = 50L,
  method = c("knn", "nn_walk"),
  distance = c("euclidean", "haversine"),
  dist_method = c("euclidean", "gower"),
  normalize = TRUE,
  parallel = TRUE,
  n_cores = NULL,
  progress = TRUE,
  seed = NULL,
  focal_points = NULL,
  focal_domain = NULL
)

Arguments

x

A site-by-species matrix (abundance or presence/absence).

coords

A data.frame with columns x and y, or a spacc_dist object.

tree

A phylogenetic tree of class phylo with branch lengths. Supply either tree or traits.

traits

A species-by-traits matrix or data.frame, row names matching the columns of x.

q

Numeric vector. Orders of diversity. Default c(0, 1, 2).

n_seeds

Integer. Number of random starting points. Default 50.

method

Character. Accumulation method: "knn" or "nn_walk".

distance

Character. Site distance method: "euclidean" or "haversine".

dist_method

Character. Trait distance for traits: "euclidean" on standardised traits (default) or "gower".

normalize

Logical. Rescale trait distances to a maximum of 1. Default TRUE.

parallel

Logical. Use parallel processing? Default TRUE.

n_cores

Integer. Number of cores.

progress

Logical. Show progress? Default TRUE.

seed

Integer. Random seed.

focal_points

Optional focal points for method = "knn". See spacc().

focal_domain

Optional polygonal focal domain. See spacc().

Details

At each accumulation step the function computes, for every order q, the taxonomic Hill number ^qD of the accumulated community and either its phylogenetic Hill number ^qD(T) (Chao et al. 2010; effective number of equally abundant, equally distinct lineages, with T the abundance-weighted mean root-to-tip depth) or its similarity-sensitive functional Hill number ^qD^Z (Leinster & Cobbold 2012; with Z = 1 - d from trait distances). The ratio

R_q = {}^qD / {}^qD(T) \quad \textrm{or} \quad {}^qD / {}^qD^Z

is at least 1, equal to 1 when species are maximally distinct (a star tree, or every pair of species at the maximal trait distance), and grows as the species added are close relatives or functionally similar to those already present. A ratio rising along the curve says the area is adding species faster than lineages or trait combinations.

Value

An object of class spacc_redundancy containing:

curves

Named list (one per q) of n_seeds x n_sites matrices of the ratio taxonomic / phylogenetic or functional Hill number

taxonomic

The taxonomic Hill numbers, same layout

dimension

The phylogenetic or functional Hill numbers, same layout

type

"phylogenetic" or "functional"

q, coords, n_seeds, n_sites, n_species, method, orders

Parameters and the site orders used

References

Chao, A., Chiu, C.-H. & Jost, L. (2010). Phylogenetic diversity measures based on Hill numbers. Philosophical Transactions of the Royal Society B, 365, 3599-3609.

Leinster, T. & Cobbold, C.A. (2012). Measuring diversity: the importance of species similarity. Ecology, 93, 477-489.

Alberdi, A. & Gilbert, M.T.P. (2019). A guide to the application of Hill numbers to DNA-based diversity analyses. Molecular Ecology Resources, 19, 804-817. doi:10.1111/1755-0998.13014

See Also

spaccHill(), spaccPhylo(), spaccFunc(), diversityProfile()

Examples


if (requireNamespace("ape", quietly = TRUE)) {
  tree <- ape::rcoal(25)
  coords <- data.frame(x = runif(40), y = runif(40))
  species <- matrix(rpois(40 * 25, 1), nrow = 40,
                    dimnames = list(NULL, tree$tip.label))
  red <- spaccRedundancy(species, coords, tree = tree, n_seeds = 10)
  plot(red)
}



Accumulate species within an expanding radius

Description

Accumulate species within an expanding radius from seed points. Models invasion spread from introduction points.

Usage

spaccWavefront(
  x,
  coords,
  n_seeds = 50L,
  r0 = 0,
  dr = NULL,
  n_steps = 50L,
  distance = c("euclidean", "haversine"),
  progress = TRUE,
  seed = NULL
)

Arguments

x

A site-by-species matrix.

coords

A data.frame with x and y columns, or a spacc_dist object.

n_seeds

Integer. Number of random starting points.

r0

Numeric. Initial radius. Default 0.

dr

Numeric. Radius increment per step. Default auto-calculated.

n_steps

Integer. Number of expansion steps. Default 50.

distance

Character. Distance method.

progress

Logical. Show progress?

seed

Integer. Random seed.

Value

An object of class spacc_wavefront containing:

curves

Matrix of species counts (n_seeds x n_steps)

radius

Vector of radius values

sites_included

Matrix of sites included at each step

References

Shigesada, N. & Kawasaki, K. (1997). Biological Invasions: Theory and Practice. Oxford University Press.

Examples


coords <- data.frame(x = runif(50), y = runif(50))
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)
wf <- spaccWavefront(species, coords, n_seeds = 20, n_steps = 50)
plot(wf)



Compute spatial eigenvectors (PCNM/dbMEM)

Description

Compute spatial eigenvectors from site coordinates using Principal Coordinates of Neighbour Matrices (PCNM) or distance-based Moran's Eigenvector Maps (dbMEM).

Usage

spatialEigenvectors(
  coords,
  threshold = NULL,
  method = c("pcnm", "dbmem"),
  distance = c("euclidean", "haversine")
)

Arguments

coords

A data.frame with columns x and y, or a spacc_dist object.

threshold

Numeric. Distance threshold for truncation. Default NULL uses the largest edge in the minimum spanning tree.

method

Character. "pcnm" (default) retains all positive eigenvectors; "dbmem" retains only those with positive Moran's I.

distance

Character. "euclidean" (default) or "haversine".

Details

PCNM (Borcard & Legendre 2002) decomposes spatial structure into orthogonal eigenvectors representing patterns at different spatial scales. Large eigenvalues correspond to broad-scale patterns (positive spatial autocorrelation), while small eigenvalues represent fine-scale patterns.

The algorithm:

  1. Compute pairwise distances

  2. Truncate distances beyond threshold (set to 4 * threshold)

  3. Double-centre the squared truncated distance matrix

  4. Extract eigenvectors with positive eigenvalues

  5. For "dbmem": additionally filter to Moran's I > 0

Value

An object of class spacc_mem containing:

vectors

Matrix of eigenvectors (sites x n_vectors)

eigenvalues

Positive eigenvalues

moran_i

Moran's I for each eigenvector

threshold

Truncation distance used

coords

Original coordinates

n_sites

Number of sites

method

Method used

References

Borcard, D. & Legendre, P. (2002). All-scale spatial analysis of ecological data by means of principal coordinates of neighbour matrices. Ecological Modelling, 153, 51-68.

Dray, S., Legendre, P. & Peres-Neto, P.R. (2006). Spatial modelling: a comprehensive framework for principal coordinate analysis of neighbour matrices (PCNM). Ecological Modelling, 196, 483-493.

See Also

spatialPartition() for variance partitioning with MEMs

Examples

coords <- data.frame(x = runif(30), y = runif(30))
mem <- spatialEigenvectors(coords)
print(mem)


Partition diversity variation into spatial and non-spatial parts

Description

Partition diversity variation into spatial and non-spatial components using forward selection of Moran's Eigenvector Maps.

Usage

spatialPartition(x, mem, metric = NULL, forward = TRUE, alpha = 0.05)

Arguments

x

A spacc result object (e.g., spacc_metrics, spacc_alpha, spacc_hill) or a numeric vector of per-site diversity values.

mem

A spacc_mem object from spatialEigenvectors().

metric

Character. Which metric to extract from x (passed to internal extraction). Default NULL uses the first available.

forward

Logical. Use forward selection? Default TRUE. If FALSE, all MEMs are included.

alpha

Numeric. Significance threshold for forward selection. Default 0.05.

Details

Forward selection of MEMs proceeds by adding the MEM that most improves the model AIC at each step, stopping when no MEM improves AIC by more than 2 units or when p > alpha.

Value

An object of class spacc_mem_partition containing:

r_squared_spatial

R-squared of the spatial model

r_squared_total

Total R-squared (same as spatial here)

selected_mems

Names of selected MEM vectors

n_selected

Number of selected MEMs

anova_table

ANOVA table from the final model

coefficients

Model coefficients

See Also

spatialEigenvectors() for computing MEMs

Examples


coords <- data.frame(x = runif(30), y = runif(30))
species <- matrix(rpois(30 * 15, 2), nrow = 30)

mem <- spatialEigenvectors(coords)
alpha <- alphaDiversity(species, q = 0)
part <- spatialPartition(alpha$q0, mem)
print(part)



Rarefy with distance-weighted site sampling

Description

Compute expected species richness accounting for spatial autocorrelation (Chiarucci et al. 2009). Uses distance-weighted sampling probabilities.

Usage

spatialRarefaction(x, coords, n_perm = 100, bandwidth = NULL)

Arguments

x

A site-by-species matrix.

coords

A data.frame with x and y columns.

n_perm

Number of permutations. Default 100.

bandwidth

Distance bandwidth for spatial weighting.

Value

A data.frame with columns: sites, mean, sd, lower, upper

References

Chiarucci, A., Bacaro, G., Rocchini, D. & Fattorini, L. (2009). Discovering and rediscovering the sample-based rarefaction formula in the ecological literature. Community Ecology, 10, 195-199.


Subsample sites to reduce spatial autocorrelation

Description

Reduce spatial autocorrelation by subsampling sites using various methods.

Usage

subsample(
  coords,
  n = NULL,
  method = c("grid", "random", "thinning"),
  cell_size = NULL,
  min_dist = NULL,
  seed = NULL
)

Arguments

coords

A data.frame with columns x and y containing site coordinates.

n

Integer. Target number of sites to retain. If NULL, determined by cell_size or min_dist.

method

Character. Subsampling method: "grid" (default), "random", or "thinning".

cell_size

Numeric. Grid cell size for method = "grid". One site retained per cell.

min_dist

Numeric. Minimum distance between retained sites for method = "thinning".

seed

Integer. Random seed for reproducibility.

Details

Methods:

Value

Integer vector of row indices to retain.

References

Aiello-Lammens, M.E., Boria, R.A., Radosavljevic, A., et al. (2015). spThin: an R package for spatial thinning of species occurrence records for use in ecological niche models. Ecography, 38, 541-545.

Lennon, J.J., Koleff, P., Greenwood, J.J.D. & Gaston, K.J. (2004). Contribution of rarity and commonness to patterns of species richness. Ecology Letters, 7, 81-87.

Examples


coords <- data.frame(x = runif(50) * 100, y = runif(50) * 100)
species <- matrix(rbinom(50 * 30, 1, 0.3), nrow = 50)

keep <- subsample(coords, method = "grid", cell_size = 20)
sac <- spacc(species[keep, ], coords[keep, ])



Compute zeta diversity across orders k

Description

Compute zeta diversity — the mean number of species shared across k sites — for increasing orders of k. The zeta decline curve reveals community assembly processes: exponential decline suggests stochastic assembly, while power-law decline indicates niche-based assembly.

Usage

zetaDiversity(
  x,
  coords,
  orders = 1:10,
  n_samples = 100L,
  method = c("knn", "random"),
  distance = c("euclidean", "haversine"),
  seed = NULL,
  progress = TRUE
)

Arguments

x

A site-by-species matrix (presence/absence or abundance). Automatically binarized.

coords

A data.frame with columns x and y, or a spacc_dist object.

orders

Integer vector. Orders of zeta diversity to compute (number of sites in each combination). Default 1:10.

n_samples

Integer. Number of random combinations to sample per order. Default 100.

method

Character. Method for selecting k-site combinations: "knn" (spatially nearest sites) or "random" (random combinations). Default "knn".

distance

Character. Distance method: "euclidean" or "haversine".

seed

Integer. Random seed for reproducibility. Default NULL.

progress

Logical. Show progress? Default TRUE.

Details

Zeta diversity of order k (\zeta_k) is the mean number of species shared across k sites. Key properties:

The zeta decline ratio (\zeta_k / \zeta_{k-1}) is diagnostic:

The knn method selects spatially nearest k sites from each focal site, which is ecologically meaningful for testing spatial turnover. The random method samples random k-site combinations, providing a null expectation.

Value

An object of class spacc_zeta containing:

zeta

Mean zeta values per order

zeta_sd

Standard deviations per order

orders

The k values

n_samples

Number of samples per order

ratio

Zeta ratio: zeta_k / zeta_(k-1)

decline

Data.frame with exponential and power-law fit statistics

method

Method used

n_sites

Number of sites

n_species

Total species count

References

Hui, C. & McGeoch, M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. The American Naturalist, 184, 684-694.

Latombe, G., McGeoch, M.A., Nipperess, D.A. & Hui, C. (2018). zetadiv: an R package for computing compositional change across multiple sites, assemblages or cases. bioRxiv, 324897.

See Also

spaccBeta() for pairwise beta diversity, distanceDecay() for distance-decay relationships

Examples


coords <- data.frame(x = runif(30), y = runif(30))
species <- matrix(rbinom(30 * 20, 1, 0.3), nrow = 30)
zeta <- zetaDiversity(species, coords, orders = 1:5, n_samples = 50)
plot(zeta)