Every spacc analysis starts from the same two inputs: a table of
species per site and the positions of those sites. This article prints
the exact structures spacc() accepts, builds them from
occurrence records in long format, and shows what happens when they do
not fit together. Installation is covered in Get
started; the sf examples need the suggested package sf.
Inspect the structures
spacc()accepts for species and coordinates.Reshape long-format records into a matrix keyed by site.
Choose between abundance and incidence.
Split the input by species group or by region.
Check the errors that malformed input gives.
The two inputs
The species table x has one row per site and one column
per species. It is a numeric matrix or a data frame whose columns are
all numeric; entries are 0/1 presence or abundance counts. The
coordinates coords have one row per site, in the same order
as x. The smallest valid pair has four sites and three
species:
x <- matrix(c(1, 0, 0,
1, 1, 0,
0, 1, 1,
0, 0, 1), nrow = 4, byrow = TRUE,
dimnames = list(c("A", "B", "C", "D"), c("sp1", "sp2", "sp3")))
coords <- data.frame(x = c(0, 1, 2, 3), y = c(0, 0, 0, 0))
x
#> sp1 sp2 sp3
#> A 1 0 0
#> B 1 1 0
#> C 0 1 1
#> D 0 0 1
coords
#> x y
#> 1 0 0
#> 2 1 0
#> 3 2 0
#> 4 3 0spacc() pairs row i of x with row i of
coords; row names and site identifiers are not used for
matching. With method = "collector" the sites enter in row
order, which makes the result easy to check by hand: site A adds one
species, B one more, C the third.
spacc(x, coords, method = "collector", progress = FALSE)$curves
#> [,1] [,2] [,3] [,4]
#> [1,] 1 2 3 3Coordinate formats
coords comes in three forms. A data frame needs columns
named x and y; other columns are ignored. For
longitude and latitude, put longitude in x, latitude in
y, and pass distance = "haversine", which
measures great-circle distances in kilometres.
lonlat <- data.frame(x = c(16.30, 16.35, 16.40, 16.45),
y = c(48.20, 48.21, 48.22, 48.23))
spacc(x, lonlat, method = "nn_walk", distance = "haversine",
n_seeds = 4, progress = FALSE)
#> spacc: 4 sites, 3 species, 4 seeds (nn_walk)An sf object with point geometries is read through its
coordinates, and its coordinate reference system is kept for functions
that need it, such as support. The distance is still set by
distance: for a longitude and latitude layer, pass
distance = "haversine" as above.
pts <- sf::st_as_sf(lonlat, coords = c("x", "y"), crs = 4326)
spacc(x, pts, method = "nn_walk", distance = "haversine",
n_seeds = 4, progress = FALSE)
#> spacc: 4 sites, 3 species, 4 seeds (nn_walk)The third form is a spacc_dist object from
distances(), a precomputed distance matrix that carries the
coordinates as an attribute.
d <- distances(coords)
d
#> spacc distance matrix: 4 x 4
#> Method: euclidean
#> Distance range: 1.0 - 3.0
spacc(x, d, method = "nn_walk", n_seeds = 4, progress = FALSE)
#> spacc: 4 sites, 3 species, 4 seeds (nn_walk)Every method then takes its distances from the matrix, and the
distance argument of the call is not used.
distances() on an sf layer with longitude and
latitude computes geodesic distances in metres, so this is also the way
to run the default method on such a layer with distances measured on the
ground:
d_geo <- distances(pts)
#> Auto-detected CRS: using 'geodesic' distance
round(as.matrix(d_geo)[1, ])
#> [1] 0 3869 7737 11604
spacc(x, d_geo, n_seeds = 4, seed = 1, progress = FALSE)$orders
#> [,1] [,2] [,3] [,4]
#> [1,] 1 2 3 4
#> [2,] 4 3 2 1
#> [3,] 3 4 2 1
#> [4,] 1 2 3 4A matrix holds distances between sites and nothing else, which changes three methods:
-
knncannot measure from a focal point placed between the sites, so it takes sites as focal points, drawn with replacement, and ranks the other sites by their distance from the focal site. Each row ofordersabove starts at its focal site.focal_pointsandfocal_domainneed coordinates as input. -
kncnhas no centroid to measure from. It adds the unvisited site with the smallest sum of squared distances to the sites already visited, which for Euclidean distances is the site nearest their centroid. -
conetakes distances from the matrix and the direction of each site from the coordinates stored in the object, as bearings on the sphere when the matrix holds haversine or geodesic distances. Aspacc_distobject built by hand without coordinates has no directions, andconestops with an error.
Running on many sites covers when precomputing pays off.
From occurrence records to a matrix
Occurrence data often come in long format: one row per record, with a
site identifier, a species name and a count. A separate table lists the
sites and their coordinates. In this example records has
seven records from four sites, and site S4 was surveyed but
nothing was found.
records <- data.frame(
site = c("S1", "S1", "S2", "S2", "S2", "S3", "S1"),
species = c("Carex", "Poa", "Poa", "Festuca", "Carex", "Festuca", "Poa"),
count = c(3, 1, 2, 5, 1, 4, 2)
)
sites <- data.frame(site = c("S1", "S2", "S3", "S4"),
lon = c(10.0, 10.1, 10.2, 10.3),
lat = c(47.0, 47.0, 47.1, 47.1))xtabs() sums the counts into a site-by-species table
keyed by the site identifier. Setting the site levels from
sites keeps S4 as a row of zeros; without it,
a site with no records would drop out and the two tables would no longer
have the same rows. The two Poa records at S1
add up to 3.
records$site <- factor(records$site, levels = sites$site)
tab <- xtabs(count ~ site + species, data = records)
mat <- as.matrix(as.data.frame.matrix(tab))
mat
#> Carex Festuca Poa
#> S1 3 0 3
#> S2 1 5 2
#> S3 0 4 0
#> S4 0 0 0The coordinates are then put in the row order of the matrix by matching identifiers, never by assuming both tables are already sorted the same way. The check stops with an error if a site of the matrix has no coordinates.
idx <- match(rownames(mat), sites$site)
stopifnot(!anyNA(idx))
xy <- data.frame(x = sites$lon[idx], y = sites$lat[idx])
spacc(mat, xy, method = "nn_walk", distance = "haversine",
n_seeds = 4, progress = FALSE)
#> spacc: 4 sites, 3 species, 4 seeds (nn_walk)A site table with a species column per site, as written by a
spreadsheet, needs no reshape: keep the species columns as
x and the coordinate columns, renamed to x and
y, as coords. Reading your own data in
Get started shows this with a CSV file.
Abundance or incidence
spacc() and the other richness curves only ask whether a
species is present, so they treat every count above zero as a presence.
The abundance matrix and its 0/1 version give identical curves.
inc <- (mat > 0) * 1
a <- spacc(mat, xy, method = "collector", progress = FALSE)
b <- spacc(inc, xy, method = "collector", progress = FALSE)
identical(a$curves, b$curves)
#> [1] TRUESome functions use the counts themselves. Hill numbers of order 1 and
2 (spaccHill()), sample coverage
(spaccCoverage()), individual-based rarefaction
(rarefy()) and the abundance estimators
(chao1(), ace()) need abundances, and give
different or meaningless results on 0/1 data. The incidence estimators
(chao2(), jackknife()) use presence across
sites and accept either.
The comparison below reads the Hill numbers of order 0 and 2 after all four sites, once from the counts and once from the 0/1 matrix.
final_hill <- function(m) {
h <- spaccHill(m, xy, q = c(0, 2), method = "nn_walk",
distance = "haversine", n_seeds = 4, progress = FALSE)
d <- as.data.frame(h)
setNames(d$mean[d$sites == 4], paste0("q", d$q[d$sites == 4]))
}
rbind(abundance = final_hill(mat), incidence = final_hill(inc))
#> q0 q2
#> abundance 3 2.655738
#> incidence 3 3.000000Richness (q = 0) is the same in both rows. The q = 2 value differs because it weighs species by their counts, which the 0/1 matrix has lost.
Grouped inputs
Two arguments split one input into several curves.
groups assigns each species, that is each column of
x, to a group, for example native and alien species; it has
one entry per column. Every group is accumulated along the same site
orders.
status <- c(Carex = "native", Festuca = "native", Poa = "alien")
grp <- spacc(mat, xy, method = "nn_walk", distance = "haversine",
n_seeds = 4, groups = status[colnames(mat)], progress = FALSE)
grp
#> spacc: 2 groups (nn_walk)
#> native: 4 sites, 2 species
#> alien: 4 sites, 1 speciesThe vector is indexed by colnames(mat), so each label
follows its species whatever the column order. support
splits by region instead: it restricts the starting points to sites
inside a polygon or country, and support = "auto" runs one
curve per country the sites fall in. Both return a grouped
spacc object; Comparing
curves between groups and regions covers them with a full
example.
Errors from malformed input
spacc() checks the shape of its inputs before it
computes anything. The calls below reuse mat and
xy from From
occurrence records to a matrix.
A species table with a text column, such as a site identifier left in the data frame, is rejected:
spacc(data.frame(site = rownames(mat), mat), xy, progress = FALSE)
#> Error:
#> ! Species matrix must be numeric (presence/absence or abundance data)Coordinates without columns named x and
y:
spacc(mat, sites[, c("lon", "lat")], progress = FALSE)
#> Error in `.resolve_coords()`:
#> ! coords must have x and y columnsA species table and coordinates with different numbers of rows:
spacc(mat[-4, ], xy, progress = FALSE)
#> Error in `spacc()`:
#> ! x and coords must have same number of rowsA groups vector with one entry per site instead of one
per species:
spacc(mat, xy, groups = c("a", "a", "b", "b"), progress = FALSE)
#> Error in `spacc()`:
#> ! groups must have length equal to ncol(x)Some problems raise no error. Coordinates sorted differently from the
species table have the right number of rows and are accepted, so the
species are attached to the wrong sites; the keyed match()
above prevents this. Negative values count as absences, because only
counts above zero are presences.
A missing entry is an error. NA can stand for a species
that was looked for and not found or for a site that was not surveyed,
and the two call for different repairs: replace the first kind by 0 and
drop the sites of the second kind.
with_na <- mat
with_na[2, 1:2] <- NA
spacc(with_na, xy, progress = FALSE)
#> Error:
#> ! Species matrix has 2 missing values (NA) in 1 site. Replace NA by 0 where the species was looked for and not found, or drop the sites that were not surveyed.
anyNA(mat)
#> [1] FALSE