Skip to contents

Records with uncertain coordinates, one record per cell, thinning, background strategies and recording effort, and how much these choices change the data design.

6. Imprecise records: keep, propagate or drop

Records are usually dropped above a fixed coordinate uncertainty, e.g. 1 km. That discards many usable records, often the older ones and those from poorly sampled regions, and narrows the sampled niche: 5 km of uncertainty on a plain changes the climate of a record very little, while 1 km on a steep slope can change it a lot. uncertainty_environment() measures this directly. For each record it finds the cells that its uncertainty circle touches and divides the range of every predictor among them by the breadth of the species’ niche on that predictor (the distance between the 5th and 95th percentile of the values at all records):

u <- uncertainty_environment(occ, env, max_rel = 0.1)
table(u$unc_ok, useNA = "ifany")
occ_ok <- u[which(u$unc_ok), ]

unc_ok is TRUE when the true conditions cannot differ from the recorded ones by more than max_rel (here a tenth) of the niche breadth on any layer. unc_rel_<layer> gives the value for each layer and unc_limiting the layer that decides. Records without an uncertainty get NA (or assume one with na_uncertainty); records above max_radius_km are rejected without being examined. Use the layers and the resolution you will model with, and run filter_occurrences() with a generous max_coord_unc_m beforehand.

Propagate instead of dropping. A record whose environment varies within its radius need not be dropped: its uncertainty can be carried into the models. unc_action says what to do with each record: "keep" (uniform environment), "propagate" (it varies) or "drop" (radius above max_radius_km). Models built from positionally uncertain records can remain ecologically interpretable: in simulations, positional error lowered predictive performance more than it changed variable importance and response shapes, especially for spatially homogeneous predictors (Gabor et al. 2023, Ecography e06358). jitter_uncertainty() makes n replicate datasets in which every record is moved to a random point within its own uncertainty circle (uniform over its area), optionally only inside M, on land and in cells with values in every layer; records with an uncertainty of 0 do not move, and records without one stay fixed or get a default radius (na_uncertainty):

j <- jitter_uncertainty(occ, env, n = 20, m = m_area, land = "land.gpkg",
                        seed = 1)
j                       # IN SHORT: is propagating worth the extra runs?
plot_jitter(j)          # per record: uncertainty against environmental change
for (d in j$replicates) {
  # thin_by_cell(d, env), fit the model in your software, predict, save
}
write_jitter(j, "jittered")                       # or one CSV per replicate
How much the predictors vary at the replicates of each moved record
How much the predictors vary at the replicates of each moved record

The printout answers the practical question: how many records change their environment by more than max_rel of the niche breadth across the replicates (the same scale as uncertainty_environment()). If almost none do, the replicates are environmentally the same dataset and propagating is not worth the model runs. propagate = "variable" moves only the records that uncertainty_environment() marks as "propagate", keeping the others where they are. After modelling, coordinate_spread() turns the replicate predictions into the spread due to coordinate error (section 25.1 below). Coordinates can also be optimised within the radius against model performance (Wu et al. 2026, Environmental Modelling & Software 204, 107096); that needs the model and is left to the modelling software.

7. One point per raster cell and background points

After filtering, merge your sources, keep one record per cell of the predictor rasters, and draw background points from the same grid:

env <- crop_to_m(env, m)                     # predictors within M (see above)

occ <- merge_occurrences(sNMF = "genetic_samples.csv",   # your own samples
                         GBIF = clean,                     # filtered GBIF
                         species = "Genus species")
pres <- thin_by_cell(occ, env, priority = c("sNMF", "GBIF"))  # own samples win
bg   <- sample_background(env, n = 10000, n_sets = 10,
                          exclude = pres, seed = 123)

write.csv(pres[c("species", "lon", "lat")], "presences_1perCell.csv",
          row.names = FALSE)
for (k in unique(bg$set)) {
  write.csv(bg[bg$set == k, c("lon", "lat")],
            sprintf("background_10000_set%d.csv", k), row.names = FALSE)
}

thin_by_cell() moves each kept record to the centre of its cell and keeps the original coordinates in lon_orig / lat_orig. Records outside the rasters, or in cells where any layer has no value, are dropped. sample_background() draws only from cells where all layers have values, one point per cell, with an independent, reproducible seed for each set.

8. Environmental thinning and thinning by distance

One record per cell still leaves densely sampled regions (e.g. typically Western Europe, North America etc.) over-represented in environmental space. thin_environment() evens out that density without choosing a target number, while keeping the environmental coverage of all records (the observed coverage, which is not the same as the species’ niche: the records only sample it):

th <- thin_environment(pres, env,
                       radius_km = 1,          # positional accuracy of records
                       protect = list(source = "sNMF"),  # always kept
                       block_km = 50, block_min = 2,     # geographic quota
                       seed = 1)
th                                   # what was kept and why; checks
plot_env_thinning(th)                # PC pairs and the map, kept vs removed
write_env_thinning(th, "out", "presences_envThinned")
pres_env <- kept(th)
Kept and removed records in environmental space and on the map
Kept and removed records in environmental space and on the map

How it works:

  1. A PCA of the whole area (random cells of env, precipitation amounts log-transformed) gives the environmental space; the first PCs with 95% of the variance are used (axes = "raw" for standardised layers).
  2. The bin width comes from the data: the range of each axis among the cells within radius_km of a record (at least the 3 x 3 cells around it, since its position within its cell is unknown) is its environmental uncertainty; the median over records is the bin width. Two records in one bin differ less than one record’s own uncertainty.
  3. One record per occupied bin is kept (the most central). Every removed record therefore has a kept neighbour less than one bin away on every axis: only density changes, not the occupied space.
  4. Always kept: protected records, the minimum and maximum of every layer, and the convex-hull vertices of every pair of axes (extreme combinations). With protect_rare (e.g. 0.05), also that share of the records with the most isolated combinations of conditions in the full environmental space.
  5. A geographic quota keeps at least block_min records in every block_km equal-area block, choosing the least represented environments first, so isolated areas are not lost.

The bin width is one for all records, but each record’s own environmental uncertainty is not: in varied surroundings (mountains) it spans several bins, in uniform ones (lowlands) a fraction of one. Records in varied places therefore fall into different bins more easily and are thinned more gently; the printout gives the spread of the uncertainty and the share kept in the most uniform and the most varied third. The PCA keeps the axes with 95% of the variance, and a variable with little overall variance can still matter to the species: compare axes = "raw" or pc_cumvar = 0.99 with bias_sensitivity(env_thin_args = ...).

The report shows that the ranges of all layers are identical before and after, how far removed records are from kept ones, and how the number of occupied bins changes with the bin width. Pass template = th to thin a subset (e.g. one lineage) in exactly the same space.

Thinning by distance, the most widely used alternative, keeps no two records closer than a distance. thin_distance() removes the record with the most neighbours within it first, as spThin does (Aiello-Lammens et al. 2015), and repeats the thinning: the run that keeps the most records is returned, and all runs are kept, so that models can be fitted to several and their predictions compared. It evens out records on the map, not in environmental space: in simulations it lost 7-25% of the records holding the minimum or maximum of a variable, which thin_environment() keeps by design (validation/). bias_sensitivity() compares both, and other designs, on the same records.

td <- thin_distance(pres, dist_km = 10, n_rep = 20)
td                                    # records kept, spread among the runs
pres_10km <- td$data[td$data$kept, ]

Any single thinning is one of many valid solutions. thin_distance() keeps all its runs, and thin_environment(n_rep = 10) adds ten runs in the same space and bins with a random record per bin; fit a model to several and compare the predictions (e.g. with coordinate_spread()) to see how much they depend on which records survived. To keep every record instead, record_weights() weights each by the inverse of the number of records within a distance: a cluster then counts about as much as the one record thinning would keep, and the weights go to the modelling software as case weights of the presences.

rw <- record_weights(pres, dist_km = 10)
rw                                    # effective sample size
pres$weight <- rw$data$weight

9. Background strategies and recording effort

sample_background(method = ...) offers six ways to draw background points (each with n_sets reproducible sets):

method Background Use
"uniform" (default) random cells the classic choice
"envstrat" even coverage of environmental bins (PCA of the layers) common climates no longer dominate the background
"effort" cells weighted by recording effort like a target-group background: corrects the sampling bias of presences
"enveffort" environmental bins with equal weight, effort-weighted cells within each bin both corrections at once
"target_group" cells weighted by the records of a target group (genus, family, … recorded by the same people), raw or kernel-smoothed, optionally weighted by observer and stratified by environment the dominant bias correction; see below
"aggregation" cells weighted by how densely the presences themselves cluster around them in environmental and geographic space (Xu et al. 2024) bias correction without a target group; see below

No strategy is best for every species: which one gives the most transferable models depends on how biased the records are and on how the species’ niche lies in the study area. Treat the method as one more choice to test: fit models with two or more backgrounds and compare them on the same hold-out folds and, where available, on independent (e.g. fossil) records; "uniform" is a sound reference.

The methods also answer different questions. Uniform sampling represents how conditions are available in the area; effort weighting represents where people record, the bias the presences share; environmental stratification gives each environmental class equal weight, which changes the distribution the presences are compared with rather than representing availability better. A target group is only a good correction if it shares the focal species’ observation process (the same recorders, methods and periods). target_group_check() compares the two sets of records where (the share of focal records in grid cells with target records), when (the distribution of years) and how (the mix of basisOfRecord) they were made:

tg <- target_group_check(focal_records, target_records, grid_km = 10)
tg                                   # same where, when and how?
plot_target_group(tg, "years")
Years of the focal and the target-group records
Years of the focal and the target-group records
bg <- sample_background(env, n = 10000, n_sets = 10, exclude = pres,
                        method = "enveffort", effort = effort$n_species,
                        seed = 123)

Recording effort from GBIF. One SQL download counts, per cell, all vascular-plant records, the number of species recorded (the recommended proxy) and records of companion species:

q <- gbif_effort_sql(extent = c(-32, 75, 34, 82), cell = 0.1,
                     target = c("Silene acaulis", "Salix herbacea"))
tab <- download_gbif_effort(q, "gbif_effort")   # takes minutes to hours
effort <- gbif_effort_rasters(tab, c(-32, 75, 34, 82), cell = 0.1,
                              path = "gbif_effort")

This needs a free GBIF account and the rgbif package. Never write your password in a script. Store the credentials once in your .Renviron file: run file.edit("~/.Renviron") in R, add

GBIF_USER=your_user_name
GBIF_PWD=your_password
GBIF_EMAIL=your_email

save, and restart R. Cite the download DOI written to gbif_effort/effort_download_DOI.txt.

Target-group background. Background drawn where related species were recorded carries the same sampling bias as the presences. Among four common corrections it emulated known sampling effort best, though it sometimes overcompensated, so check the maps for realism (Barber et al. 2021, Diversity and Distributions 28, 128-141). gbif_target_group_sql() builds the GBIF download of a genus, family or other group without your species, record by record (with recordedBy) or counted per cell:

q  <- gbif_target_group_sql(extent = c(5, 17, 43, 48),
                            group = c(family = "Rosaceae"),
                            exclude_species = "Genus species",
                            years = c(1980, 2025))
tg <- download_gbif_effort(q, "target_group")
bg <- sample_background(env, n = 10000, method = "target_group",
                        target = tg, target_bandwidth_km = 5,   # kernel (km)
                        exclude = pres, seed = 123)
  • target_bandwidth_km = 0 uses the records per cell (the classic target-group background); a bandwidth smooths them with a Gaussian kernel. Balej et al. (2025, Ecography e08202) recommend this smoothed version (“TGOB+”) when no independent data are available; no single bandwidth was best, so try a few (e.g. 1, 2 and 4 cell widths).
  • target_observer = "recordedBy" with presences weights each observer’s normalised density by their share of the records of your species (their PW-OOA method, the best when checked against independent data).
  • target_stratify = TRUE combines the target density with the environmental bins of "enveffort".

Aggregation background. Without a target group, the sampling bias can be estimated from the presences themselves. method = "aggregation" weights each cell by the kernel density of the presences on each standardised layer, each presence weighted by the inverse of its geographic distance (aggregation_k = 1; 0 uses the environment only, their “similarity background”), averaged over the layers (Xu et al. 2024, Ecological Informatics 81, 102604). In their simulations it was more accurate than the target-group background, and better than spatial filtering with up to about 70 presences:

bg <- sample_background(env, n = 10000, method = "aggregation",
                        presences = pres, seed = 123)

Background thickening. Instead of removing clustered presences, the background can be clustered like them: method = "thickening" draws each cell with a probability proportional to the number of presences within a radius, by default the mean range of the semivariograms of the layers (Vollering et al. 2019, Ecography 42, 1717-1727). No presence is discarded; in their simulations it beat thinning with 25 presences and lost to it with 250, so it suits small samples:

bg <- sample_background(env, n = 10000, method = "thickening",
                        presences = pres, seed = 123)
attr(bg, "background")$thickening$radius_km

Effort from accessibility. Without records of a target group (herbarium data, national databases, historical records), effort can be estimated from how accessible each place is. accessibility_effort() turns the distance to the nearest road or path, settlement and water body into a proximity that falls to 0.37 at scale_km and averages them, as Monsarrat et al. (2019, Ecography 42, 125-136) did for historical records. Supply roads and paths yourself (e.g. an OpenStreetMap extract from https://download.geofabrik.de, which includes tracks and mountain paths), settlements as points or as the built-up layer of aggregate_ghs(); or give country to download the main roads and places of OpenStreetMap with geodata::osm(). The result is an effort raster for sample_background(), effort_layers() and delimit_m(effort = ):

acc <- accessibility_effort(env, roads = "roads_and_paths.shp",
                            settlements = ghs[["mean"]], source_min = 500,
                            scale_km = 5)
acc                                  # distances to each source
bg <- sample_background(env, n = 10000, method = "effort", effort = acc)

Effort as a covariate. The corrections above change which records or background points enter the model. The other family keeps every record and lets the model separate the species from the recording: effort enters as a further predictor, and the map is predicted with effort held at the same value everywhere (Warton et al. 2013, PLoS ONE 8, e79168). This discards no record, which matters most for small samples. effort_layers() aligns an effort raster to the predictors, transforms it (log by default) and returns the layer to fit with and a constant layer to predict with, set to the maximum effort or, more conservatively, a high quantile. It also reports how strongly effort follows each predictor: where it does, the model cannot tell recording from the environment, and part of the environmental response is removed with the bias.

el <- effort_layers(effort$n_records, env, predict_at = "quantile", q = 0.95)
el                                   # the recipe and the correlations
# fit:     predictors + el$layers$effort
# predict: predictors + el$layers$effort_constant, renamed to "effort"

How many background points? The number and the spread of background points change presence-background models in a species-dependent way (Whitford et al. 2024, Ecological Modelling 488, 110604). background_sufficiency() answers the part that does not depend on the model: how many points represent the environment of M. It draws the background (with your method and arguments) at an increasing series of n and returns the saturation curve: the share of the environmental bins of M holding a background point, the share of its area, and the largest Kolmogorov-Smirnov distance of the marginal distributions. The printout gives the n at which coverage saturates and says whether the usual 10 000 is enough:

bs <- background_sufficiency(env, ns = c(1000, 2500, 5000, 10000, 25000),
                             method = "target_group", target = tg,
                             n_presences = nrow(pres))
bs
plot_background_sufficiency(bs, file = "background_sufficiency")
Coverage of the environment of M and the Kolmogorov-Smirnov distance against the number of background points
Coverage of the environment of M and the Kolmogorov-Smirnov distance against the number of background points

This is a lower bound for representing M, not the best number for a model: in simulations the most accurate current predictions came from about 0.5-1 background points per presence or about 5% of the cells, and the number mattered little for projections to future climates (Rausell-Moreno et al. 2025, Ecological Modelling 507, 111177).

10. Which bias correction? Sensitivity of the data design

First, how aggregated are the records, and is it the species or the recording? sampling_aggregation() measures Morisita’s index of the records at several grains against random points in the area; with target (records of a group recorded in the same way) it tells clustering that follows recording from a species that is patchier than recording, as in a fragmented distribution:

sa <- sampling_aggregation(pres, env_m, target = target_records,
                           grains = c(5, 10, 25, 50, 100))
sa
plot_sampling_aggregation(sa)
Morisita index of the records across grains, relative to random points
Morisita index of the records across grains, relative to random points

Sections 7 to 9 offer several corrections of sampling bias, and none can be chosen from first principles: there is no optimal spatial filtering distance (Lamboley & Fourcade 2024, Journal of Biogeography 51, 1783-1794), thinned records often did no better than the same number of records removed at random (Ten Caten & Dallas 2023, Ecosphere 14, e4703), and the best correction depends on the structure of the bias and can make predictions worse for narrow niches (Inman et al. 2021, Ecosphere 12, e03422). Without independent test data, internal evaluation is a poor guide to whether a correction helps, so present models with and without correction (Baker et al. 2024, Diversity and Distributions 30, e13802).

bias_sensitivity() makes the choice transparent on the data side. It applies a grid of corrections and reports how each changes the design; it fits no model and reports no predictive performance.

bs <- bias_sensitivity(
  occ, env_m,
  thin = c("none", "cell", "distance", "environment"),
  thin_km = c(5, 10, 25, 50), env_mult = c(1, 2),
  background = list(uniform = list(),
                    target  = list(method = "target_group", target = tg)),
  bg_n = c(1000, 10000))
bs                                        # IN SHORT: what matters, what does not
plot_bias_sensitivity(bs, "n", "env_coverage")
plot_bias_sensitivity(bs, "bg_coverage", "overlap")
Records kept against the environmental coverage of M for each thinning design
Records kept against the environmental coverage of M for each thinning design

For each thinning design: records kept; the share of the environmental bins of M that hold a record and of the records’ own bins still occupied; the same coverage for random subsets of the same size (does the thinning keep more environment than losing records at random?); the Clark-Evans ratio of nearest-neighbour distances; the range of each layer still spanned and the gaps to the limits of M (as in niche_truncation()); and the shift from the uncorrected records in environmental space. For each background: its coverage of M, its shift from a uniform background, and its overlap with the records. The printout names the choices that change the design most and those that barely matter, and the thinning designs that leave the niche intact.