Getting started with spacc

spacc builds species accumulation curves in which sites enter the count in spatial order: starting from a point in the study area, the nearest sites are added first. This tutorial starts from a table of species records per site and a table of site coordinates, and ends with a spatial accumulation curve, its summary and plot, a test against the classical random-order curve, and one short example of each analysis built on the same orders. It assumes basic R: matrices, data frames and function calls.

Installation

Install the released version from CRAN:

install.packages("spacc")

The development version is on GitHub:

# install.packages("pak")
pak::pak("gcol33/spacc")

The development version compiles C++ code; Installation shows how to set up a compiler.

A first accumulation curve

The examples use a simulated survey: 80 sites scattered over a 100 by 100 square and 40 species. Each species has a centre, and its chance of occurring at a site falls with the squared distance to that centre, so every species occupies a patch about 60 units across. Neighbouring sites therefore share species, which is the situation spatial accumulation is built for.

library(spacc)
set.seed(42)
n_sites <- 80
n_species <- 40
coords <- data.frame(x = runif(n_sites, 0, 100), y = runif(n_sites, 0, 100))
species <- matrix(0L, n_sites, n_species)
for (j in seq_len(n_species)) {
  cx <- runif(1, 20, 80)
  cy <- runif(1, 20, 80)
  p <- exp(-0.001 * ((coords$x - cx)^2 + (coords$y - cy)^2))
  species[, j] <- rbinom(n_sites, 1, p)
}
colnames(species) <- paste0("sp", seq_len(n_species))

spacc() takes two inputs. species is the site-by-species matrix: one row per site, one column per species, holding 0/1 presence or abundance counts. coords holds the site positions in columns x and y, one row per site in the same order as species; the two tables are matched by row position, not by a key. n_seeds sets how many curves are drawn, each from a different starting point.

sac <- spacc(species, coords, n_seeds = 30, progress = FALSE)
sac
#> spacc: 80 sites, 40 species, 30 seeds (knn)

The result is a spacc object; the inputs are left unchanged. Its element curves is a matrix with one row per seed and one column per accumulation step: entry (s, k) is the number of species found in the first k sites visited from seed s. Abundances count as presences here, since a curve only asks whether a species is new.

dim(sac$curves)
#> [1] 30 80
sac$curves[1:3, 1:8]
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#> [1,]   15   20   21   22   29   31   35   36
#> [2,]    3    6   11   11   14   17   19   21
#> [3,]    7   12   13   19   20   21   21   25

Every seed ends at the same value, the 40 species of the whole survey, so seeds differ only in how fast they get there. summary() reduces the seeds to a mean curve and a band between the 2.5% and 97.5% quantiles of the seeds at each step. Saturation is the first step at which the mean curve reaches 90% of its final value (saturation_threshold changes the 90%). The CV at midpoint is the standard deviation across seeds divided by the mean, halfway along the curve, in percent.

summary(sac)
#> Spatial Species Accumulation Curve
#> ------------------------------------ 
#> Method:           knn 
#> Seeds:            30 
#> Sites:            80 
#> Total species:    40 
#> Final species:   40.0 (95% CI: 40.0 - 40.0)
#> Saturation (90%): 18 sites
#> CV at midpoint:  0.9%

plot() draws the mean curve and the band. A wide band means the species found in the first sites depend strongly on where the survey starts. ci_level sets the width of the band and ci = FALSE leaves it out.

plot(sac)

Spatial accumulation curve: the mean number of species rises from about ten at one site to forty at eighty sites, with a shaded band that is widest in the first third of the curve.

as.data.frame() returns the same summary as a table, one row per step, for your own plots or for export.

head(as.data.frame(sac), 3)
#>   sites     mean lower upper       sd
#> 1     1 10.50000 1.725    18 5.230877
#> 2     2 15.83333 4.900    32 8.292428
#> 3     3 19.20000 5.900    38 9.278823

Comparing with random order

The classical accumulation curve adds sites in random order. The same call with method = "random" draws it, and c() combines named curves into one object that plot() overlays.

rnd <- spacc(species, coords, n_seeds = 30, method = "random",
             progress = FALSE)
both <- c(spatial = sac, random = rnd)
plot(both)

Two accumulation curves on the same axes: the random-order curve rises faster than the spatial curve and both reach forty species at eighty sites.

The random curve rises faster because each step mixes sites from different patches, while the spatial curve keeps adding neighbours that share species. compare() tests the difference in the area under the two mean curves by permuting seeds between them.

set.seed(1)
compare(sac, rnd, n_perm = 199)
#> Comparison: sac vs rnd 
#> ---------------------------------------- 
#> Method: permutation (n=199)
#> AUC difference: -114.9 (p = 0.005**)
#> Saturation: sac at 18 sites, rnd at 9 sites
#> 
#> rnd saturates faster.

Six other ordering rules and user-supplied orders are compared in Choosing an accumulation order; grouped curves and the tests in compare() are covered in Comparing curves between groups and regions.

Reading your own data

Field data often sit in one file with a site identifier, coordinates under other names, and one column per species. The file below is written to a temporary path so this page runs anywhere; it uses plot, easting and northing for the identifier and coordinates.

field <- data.frame(plot = sprintf("P%02d", seq_len(n_sites)),
                    easting = coords$x, northing = coords$y, species)
path <- tempfile(fileext = ".csv")
write.csv(field, path, row.names = FALSE)

Read the file, keep the species columns as a matrix, and rename the coordinate columns to x and y. Because both tables come from the same rows, their order matches.

dat <- read.csv(path)
sp_cols <- setdiff(names(dat), c("plot", "easting", "northing"))
x <- as.matrix(dat[, sp_cols])
xy <- data.frame(x = dat$easting, y = dat$northing)
spacc(x, xy, n_seeds = 30, progress = FALSE)
#> spacc: 80 sites, 40 species, 30 seeds (knn)

For another file, change the path in read.csv() and the three column names in setdiff() and data.frame(). Records in long format (one row per species and site), longitude and latitude, and sf points are covered in Preparing site-by-species data.

Common errors

The errors below come from the two input tables not fitting together. Each entry shows the message and the corrected call.

A site table with the identifier still in it is not numeric:

spacc(dat[, c("plot", sp_cols)], xy, progress = FALSE)
#> Error:
#> ! Species matrix must be numeric (presence/absence or abundance data)

Keep only the species columns, as x in Reading your own data does:

spacc(dat[, sp_cols], xy, n_seeds = 30, progress = FALSE)
#> spacc: 80 sites, 40 species, 30 seeds (knn)

Coordinates under their original names are not found:

spacc(x, dat[, c("easting", "northing")], progress = FALSE)
#> Error in `.resolve_coords()`:
#> ! coords must have x and y columns

Rename them to x and y:

names(xy)
#> [1] "x" "y"
spacc(x, xy, n_seeds = 30, progress = FALSE)
#> spacc: 80 sites, 40 species, 30 seeds (knn)

Filtering one table and not the other leaves different row counts:

keep <- dat$easting < 50
spacc(x[keep, ], xy, progress = FALSE)
#> Error in `spacc()`:
#> ! x and coords must have same number of rows

Apply the same filter to both:

spacc(x[keep, ], xy[keep, ], n_seeds = 30, progress = FALSE)
#> spacc: 36 sites, 40 species, 30 seeds (knn)

A filter that drops rows from both tables keeps them paired. Sorting one table and not the other raises no error, because the row counts still agree; the species are then attached to the wrong sites.

Other measures along the same orders

Each function below visits the sites in the same spatial orders as spacc() and counts something other than species. One short call shows what it returns; the linked article covers it in full. The abundance matrix abund gives each species a Poisson count at every site, since several of these measures weigh species by their abundance.

set.seed(7)
abund <- matrix(rpois(n_sites * n_species, lambda = 2), n_sites, n_species)
colnames(abund) <- colnames(species)

Hill numbers

Hill numbers of order q count effective species: q = 0 is richness, q = 1 the exponential of Shannon entropy, q = 2 the inverse Simpson index.

hill <- spaccHill(abund, coords, q = c(0, 1, 2), n_seeds = 20,
                  progress = FALSE)
plot(hill)

Three Hill-number accumulation curves: q = 0 highest, q = 1 in the middle, q = 2 lowest.

Accumulating Hill numbers and partitioning diversity covers the orders, the alpha, beta and gamma partition, and evenness.

Beta diversity

spaccBeta() measures how different each new site is from the sites already visited, split into turnover (other species) and nestedness (a subset of the same species) after Baselga (2010).

beta <- spaccBeta(species, coords, n_seeds = 20, progress = FALSE)
as.data.frame(beta)[c(1, 5, 20), 1:4]
#>    sites beta_total beta_turnover beta_nestedness
#> 1      1  0.5342832     0.3912383       0.1430448
#> 5      5  0.5701403     0.1254167       0.4447236
#> 20    20  0.5344867     0.0247890       0.5096977

Each row is a step of the walk, comparing the next site with the sites visited so far.

Accumulating beta diversity covers the indices and the Hill-number version.

Sample coverage

Sample coverage is the estimated share of all individuals in the community that belong to species already recorded. spaccCoverage() tracks it along the walk, and interpolateCoverage() reads the richness reached at chosen coverage levels.

cov <- spaccCoverage(abund, coords, n_seeds = 20, progress = FALSE)
colMeans(interpolateCoverage(cov, target = c(0.90, 0.95)))
#>      C90      C95 
#> 35.94299 38.02075

Standardising by sample coverage explains the estimators and when to standardise by coverage.

Total richness

Nonparametric estimators infer how many species were missed from the species seen only once or twice. chao2() uses incidence: how many species occur at one site and how many at two.

chao2(species)
#> Richness Estimator: chao2
#> -------------------------------- 
#> Observed species (S_obs): 40
#> Estimated richness:       40.0
#> Standard error:           0.0
#> 95% CI:                   [40.0, 40.0]

Every species of the simulated survey occurs at ten or more sites, so no species is seen at only one or two, and the estimate equals the observed 40.

Estimating total richness compares the estimator family.

Extrapolation

extrapolate() fits an asymptotic model to the mean curve; its asymptote is an estimate of the richness a complete survey would record.

fit <- extrapolate(sac, model = "michaelis-menten")
fit
#> Extrapolation: michaelis-menten 
#> -------------------------------------- 
#> Estimated asymptote: 42.8 species
#> 95% CI (bootstrap):       40.8 - 48.7
#> Observed:            40.0 species (94% of estimated)
#> AIC: 170.0   RMSE: 0.67 (1.8% of mean)
#> Reliable to ~200 sites (2.5x sampled effort of 80)
#> -------------------------------------- 
#> Nonparametric:  chao2 = 40.0   iChao2 = 40.0
#> (prefer these for calibrated total-richness intervals; see ?extrapolate)

Extrapolating curves and predicting richness compares the models and their predictions.

Distance decay

betaDecay() relates the dissimilarity of every pair of sites to the distance between them and fits a decay model.

betaDecay(species, coords, model = "exponential", progress = FALSE)
#> Beta distance-decay: 80 sites, 3,160 pairs
#> Index: sorensen, Distance: euclidean
#> 
#> Fitted models:
#>   exponential: a=0.6873, b=0.024703, AIC=-3681.0 *
#> 
#> Best model: exponential
#> Half-life (exp): 28.06

Measuring distance decay and zeta diversity covers distance decay and zeta diversity.

Per-site maps

spaccMetrics() runs one curve from every site and reduces each to a few numbers, such as the area under the curve, giving one value per site to map.

m <- spaccMetrics(species, coords, metrics = c("slope_10", "auc"),
                  progress = FALSE)
head(as.data.frame(m), 3)
#>   slope_10     auc site_id        x        y
#> 1 1.964286 36.7875       1 91.48060 58.16040
#> 2 1.583333 35.7500       2 93.70754 15.79052
#> 3 3.142857 38.6000       3 28.61395 35.90283

Mapping per-site metrics and wavefronts maps these values and turns them into sf layers.

Methods shared by the results

Every result object has print(), summary(), plot() and as.data.frame(), so the calls above work the same way on a Hill, beta or coverage object. [ keeps a subset of seeds, here the first five.

sac[1:5]
#> spacc: 80 sites, 40 species, 5 seeds (knn)

plot() returns a ggplot object, so further layers are added with +. ggplot2::autoplot() returns the same figure.

ggplot2::autoplot(sac) +
  ggplot2::geom_hline(yintercept = n_species, linetype = "dashed")

The spatial accumulation curve with a horizontal dashed line at forty species.

Where next

Building curves:

Diversity:

Effort and completeness:

Spatial patterns:

Background:

References

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