Start here: ecological data analysis in R

A guided reading order for ecological data analysis in R and QGIS: diversity, ordination, GLMs, mixed models and spatial methods, from first steps onward.

This page is a reading order, not a feed. The tutorials below are grouped by the stage of a typical analysis, so you can follow a path instead of picking posts at random. Each section is roughly self-contained; jump to the stage you need, or read top to bottom.

If you are new to R for ecology, start with first steps and the foundations, then move to whichever data type you work with: community tables (diversity, ordination), counts and presence-absence (GLMs), grouped or repeated measurements (mixed models), or spatial layers (GIS).

If you would rather be told what to read next than choose, the course is one numbered route through the essentials, from a messy field sheet to a result you can defend. It uses tutorials from this page, in a fixed order, with a reason given for each position.

Topic pages

If you already know which subject you need, these pages take one topic on its own: what the methods do, where they break, and every tutorial on it in reading order. The rest of this page stays the route through the whole site.

  • R for ecologists - getting field data into R and ready to analyse: reading, cleaning, reshaping, joining, and a first result.
  • Species diversity in R - alpha indices, sampling effort and the unseen tail, and the three arithmetics of beta diversity.
  • Ordination in R - NMDS, PCA, RDA and CCA, the tests that go with them, and the model-based alternative.
  • Occupancy modelling in R - detection against occupancy, from single-season models to dynamic, multi-species and multi-scale versions.
  • Capture-recapture in R - abundance, survival and density from marked animals, from closed populations to spatial models.
  • Movement ecology in R - home ranges, paths, behavioural states, tag error, and step selection.
  • Population models in R - matrices, integral projection models, and joining demographic data to counts.
  • Species coexistence in R - niche and fitness differences, the storage effect, enemies, and alternative stable states.
  • Ecological time series in R - autocorrelation, cycles, wavelets, empirical dynamic modelling and early warning signals.
  • Causal inference in ecology with R - confounders, colliders, designs that identify, and the assumption you cannot test.
  • Evolutionary game theory in R - the hawk-dove ESS, replicator dynamics, the routes to cooperation, spatial games, and drift in finite populations.
  • Quantitative genetics in R - selection differentials and gradients, the breeder’s equation, the G matrix, and the Price equation.
  • Population genetics in R - allele frequencies, F-statistics, effective size and the coalescent, built from scratch and checked against simulations
  • Landscape connectivity in R - habitat pattern, cost surfaces and circuit theory, and the genetic data that tests whether a connectivity map means anything
  • Conservation decisions in R - reserve selection, reintroduction and restoration, and the decision analysis that turns a model into a defensible choice
  • Bayesian computation in R - Metropolis, Gibbs, Hamiltonian Monte Carlo, the Laplace approximation and ABC written by hand, with the diagnostics that read them
  • Reproducible workflows in R - testing, debugging, profiling, dependency pinning, pipelines, packaging and version control, each scored against the failure it prevents
  • Data provenance checks in R - testing a dataset against the record it came from: the frame, the protocol, the recording grid and the species list, with the cost of each gap measured

First steps: getting data into R

Before any method, get your field data into R, cleaned and in the right shape. Start here if you are new to R for ecology.

Foundations

Get the basics of estimation and a reproducible setup in place before modelling anything. The estimation thread does not stop here: it picks up again further down the page, in Bootstrap and resampling inference, Multiple testing and error rates, and the Common pitfalls list at the end.

Writing analysis code you can trust

The errors that cost most are the ones that run to the end and return a plausible wrong number. These measure what each habit catches and what it misses.

Keeping a project reproducible

The result has to survive a new laptop, a package update and six months. Each of these is written by hand in base R so you can see what the tool is doing for you.

Diversity and community description

Summarise what is in your samples: richness, evenness, and the structure of an assemblage.

Diversity estimation

Go beyond what you observed: the unseen-species problem, and estimating richness and diversity from an incomplete sample.

Beta diversity

How much composition changes between sites is one number with three different arithmetics behind it, and they do not agree.

Neutral theory

What an assemblage looks like when nothing separates the species, and what it takes to test that against the alternative.

Ordination and multivariate structure

Explore gradients and group differences in multivariate community data.

Ecological networks and species interactions

Who interacts with whom, as a bipartite web. Every structural number here needs a null model before it means anything.

Food web structure and stability

Store a food web as a matrix, measure it, and ask how much of what you report is the web itself and how much is the model or the sampling.

  • Food web structure: connectance and trophic level - store a food web as a matrix and measure connectance and trophic level; why the trophic level you report is a modelling choice, not a fixed number.
  • The niche model of food webs - generate webs from one feeding axis and compare to the cascade and random models; a random graph at real connectance usually leaves no basal species.
  • Stability and complexity in food webs - May’s stability threshold in R, and how predator-prey sign structure moves the boundary far to the stable side.
  • Checking a food web analysis - three checks: sampling effort biases connectance, the null model decides significance, and the stability verdict depends on assumed self-regulation.

Classical theory in R

The models that named the field: a predator and its prey, two consumers on one resource, a host and its parasitoid, and an island filling up. Each one is written out as code, integrated or iterated by hand, and measured rather than asserted.

  • The paradox of enrichment in R - raising prey carrying capacity in a Rosenzweig-MacArthur model destabilises it through a Hopf bifurcation, and the cycle minimum falls far below any realistic extinction floor.
  • Resource competition and the R-star rule - the species that draws the limiting resource to the lowest equilibrium level wins regardless of its maximum growth rate, and two resources turn the same geometry into coexistence or bistability.
  • Aggregation and host parasitoid stability - the Nicholson-Bailey model is unstable at every parameter value, and what stabilises it is aggregated attack rather than parameter tuning.
  • Island biogeography and turnover - richness settles where immigration balances extinction while the species list keeps changing, so a constant count is not a constant community.

Animal social networks

Build a weighted network from group sightings and ask whether its structure means anything once sampling effort is accounted for.

Linear models and classical tests

The tests most ecologists meet first are one model wearing different names. Fitting that model directly puts the assumptions back where you can see them.

GLMs: families, diagnostics and interpretation

Counts, proportions and presence-absence want a family and a link, not a transformed response. This section runs the whole cycle: choose the family, find out whether it fits, and turn coefficients into something reportable.

Inference traps

None of these depend on which family you picked. They are the ways a correctly fitted model still yields a wrong conclusion, and each one is measured here rather than asserted.

Model selection and multi-model inference

Start with what AIC measures, then with what to do when no single model wins: the ranking itself carries uncertainty, so share the evidence across the candidate set instead of crowning a winner.

Finite mixture models

A histogram with bumps in it, the EM algorithm that separates them, and the harder question of whether the bumps are there at all.

Nonlinear regression

Fit a response that is nonlinear in its parameters, and read the honest limits of the fit.

Thresholds and change points

Test for a breakpoint or regime shift, and resist reading one into a smooth response.

Quantile and distributional regression

Model the quantiles or the spread, not just the mean, when the mean is not the ecology.

Generalised additive models

Let the data set the smoothness through a penalty, and know what the basis can and cannot do.

Regularisation

Trade a little bias for less variance with a penalty, and see why the naive interval no longer holds.

Tree-based and ensemble methods

Predict well with trees and ensembles, and keep prediction separate from explanation.

Flexible smoothing and predictive uncertainty

Flexible smoothers and honest prediction intervals, and why a reported interval is only a promise until you check it.

Model-based multivariate analysis

Per-species GLMs and community resampling separate what distance-based methods confound.

Traits and the environment

Traits, sites and environment meet in one cross-table. These take it apart, from a single plot average up to the two ordinations built on the same table.

Bounded and ordinal responses

Responses on the unit interval, ordered classes, and biomass with zeros, each modelled on its own scale.

Dose-response and ecotoxicology

Turning a concentration series into a number a regulator can act on, and finding out where that number actually comes from.

  • Dose-response curves and the LC50 - the LC50 is fitted rather than measured: three link functions agree there and disagree by a multiple at the LC1, where there is no data to hold them together.
  • Confidence intervals for effective doses - delta, Fieller and profile intervals scored on coverage and on sidedness, and the design choice that halves the LC10 interval at no cost in animals.
  • Hormesis and non-monotonic responses - a monotonic model fitted to stimulated data reads the low-dose end wrong, and the test for hormesis passes on designs that never observe any stimulation.
  • Checking a dose-response analysis - control mortality, vessel-level overdispersion, extrapolation below the lowest tested dose, and nominal against measured concentration.
  • NOEC rewards noisy toxicity tests - the no-observed-effect concentration climbs with replicate scatter and falls with replication, while a fitted EC10 from the same tests stays centred and only its interval widens.
  • Integrated biomarker response and axis order - the star-plot axis order moves the most impacted station less often than a repeat survey does, and a mean of standardised scores finds it just as often.
  • Sediment quality guidelines from co-occurrence - with strongly correlated chemicals the ERL/ERM incidence check passes an inert co-sourced chemical in contaminated databases and fails the real toxicant in clean ones; a joint logistic separates them unless a toxicant goes unmeasured.

Areal and lattice spatial models

On lattice data the question is not whether to model space but how, and every choice competes with a plain spatial covariance.

Time series analysis

Time-series tools mislead easily, so each one comes with an honest limit on what it can prove.

Wavelets: cycles that come and go

A periodogram averages over the whole record, so it cannot tell you when a cycle was running. A wavelet transform keeps the time axis, at the price of a null model that is harder to get right.

Early warning signals and critical transitions

Rising autocorrelation and variance before a tipping point are real, but a rising indicator is a hypothesis, not a forecast.

Empirical dynamic modelling

Rebuild the attractor from one series and test causality without a linear model. The evidence is convergence, not correlation.

MAR(1) community dynamics

A linear autoregressive model for a whole community, and the stability metrics that inherit every error the fit makes.

Evaluating ecological forecasts

A forecast is a distribution, not a number. Score the whole distribution, then ask what the score is being compared against.

  • Scoring ecological forecasts - why reducing a forecast to its mean and grading it with RMSE throws away the forecast, and what makes a scoring rule proper.
  • The CRPS and the Brier score - the Brier score for presence and absence, the CRPS for abundance or a date, and the identity that shows they are one idea at two resolutions.
  • Forecast skill and the baseline - a raw score means nothing on its own; the same forecast can look skilful or worthless depending on the reference you pick.
  • Checking a forecast evaluation - three checks: coverage on its own rewards a wide forecast, sharpness counts only after calibration, and a small test set cannot separate two forecasts.
  • Smoothing a series before testing a forecast - a smoother fitted to the whole record flatters a one-step hindcast; refitted at each forecast origin, in the same pipeline, it loses to a raw AR(1), and a filter or an endpoint regression only ties it.

Predictive model hygiene

A fitted classifier is only useful once someone acts on it, and the steps between a fitted probability and a management decision are where most of the damage happens.

  • Class imbalance in species presence models - what limits a rare-species model is the number of presences rather than the ratio, and downsampling moves the intercept by an amount you can write down.
  • Calibrating predicted probabilities in R - reliability diagrams with an honest null band, the Murphy decomposition of the Brier score, and Platt scaling and isotonic regression written out.
  • Data leakage in ecological model validation - four routes by which information crosses into the training fold, each with its measured optimism, including screening on the full dataset and splitting grouped rows.
  • Choosing a decision threshold from costs - the cost-optimal threshold, the cost ratios that popular default rules imply without saying so, and decision curves against treating every site.
  • Leave-one-out AUC on a small survey - pooling held-out predictions ranks each site with a model refitted against its own label, so on a small survey with few presences a working model scores well below its true AUC; leave-pair-out does not.
  • Classifier scores over a camera-trap sequence - why calibrated per-image scores give a miscalibrated sequence score: the closed-form slope of the averaged logit, what empty frames do to five pooling rules, and how many labelled sequences a recalibration needs.

Bootstrap and resampling inference

Resampling is a tool, not a guarantee, and each variant fails in its own way.

  • The nonparametric bootstrap - percentile, basic, normal and BCa intervals, and why only BCa handles skew correctly.
  • The parametric bootstrap - simulating from the model for a boundary test the naive chi-squared gets wrong.
  • Bootstrapping dependent data - resampling the unit of dependence with block and cluster bootstraps.
  • Cluster bootstrap at six sites, and what beats it - with six catchments and a site-level treatment the pairs cluster bootstrap and the sandwich over-reject; the site means hold the level and the wild bootstrap has a floor of 2/2^G.
  • The m out of n bootstrap - subsampling for a statistic the ordinary bootstrap gets wrong, where the rate exponent rather than the subsample size decides the interval.
  • Permutation tests from scratch - the complete enumeration, the floor a Monte Carlo p value cannot report below, and the studentised statistic that keeps its level under unequal variance.
  • Permutation tests with a covariate in the model - shuffling labels or the response mis-sizes a raw partial slope by closed-form factors; a t statistic or Freedman-Lane residuals repair both.
  • Checking a bootstrap - where a non-smooth statistic breaks, and why more data does not always fix it.
  • The jackknife and bias correction - the pseudo-values cancel the one over n term, which is what the jackknife is for, and the same estimator fails on a median where the bootstrap holds.
  • Testing a fitted distribution - a Kolmogorov-Smirnov test run with parameters estimated from the same data almost never rejects, and calibrating the null by bootstrap restores both the level and the power.

Extreme value analysis

Model the rare and the extreme: block maxima, threshold exceedances, and honest return levels for the tail of a distribution.

Circular and directional statistics

Summarise angles and times of day: directions have no arithmetic mean, and the choice of test decides the verdict.

Mixed models and correlated data

Handle grouping, pseudoreplication and correlation that ordinary regression ignores.

Phylogenetic and comparative methods

Account for shared ancestry when species are the data points, and measure phylogenetic pattern in traits.

Community phylogenetics

Bring the tree into the community table: is an assemblage more closely related than chance, and what is chance here.

Spatial data and GIS

Get occurrence records in and cleaned, then work with coordinates, rasters and the link between QGIS and R.

  • Cleaning GBIF and iNaturalist records - dropping bad coordinates, duplicates and imprecise records before any mapping.
  • Richness mapping with sf - spatial vector work and mapping in R.
  • Choosing a projection for area and distance - sf now measures unprojected data on the globe (a sphere, through s2), so the old warning about square degrees is out of date, and what still costs is which projection you pick.
  • Checking a vector layer before you measure - an invalid polygon does not throw, it answers, and a bowtie returns an area of exactly zero while a join against it still finds records.
  • What a shapefile loses - the geometry round-trips exactly and the attribute table does not: field names abbreviated past recognition, a date-time reduced to a date, a logical returned as an integer.
  • Coordinate error and habitat assignment - the share of records put in the wrong habitat class is set by the perimeter of the map rather than by the precision of the GPS, and the damage downstream is attenuation.
  • Raster basics with terra - raster structure and map algebra.
  • Slope and aspect: what a DEM does not measure - the neighbourhood rule and the cell size both change the slope you get, both of them through surface roughness, and aspect has to be split into northness and eastness before a model sees it.
  • Rasterising a vector layer - the cell rule is a measurement, not a format conversion: the centre rule loses features narrower than a cell and the touches rule invents area in proportion to edge.
  • When redrawing zones flips the sign - hold the unit count and the cells per unit fixed and move only the boundaries, and the reported relationship can change sign; a variance ratio says in advance whether your zones are able to do it.
  • LiDAR height normalisation on slopes - a cell minimum invents canopy height on a slope, sparse ground returns under closed canopy push the ground surface up, and the two errors have opposite sign.
  • QGIS to R spatial join - a hybrid workflow between the QGIS GUI and sf.
  • Running QGIS from the command line - qgis_process makes the toolbox scriptable, and the comparison with sf and terra shows where the two engines agree byte for byte and where a default quietly parts them.
  • Area in QGIS and R: which call matches which - every QGIS area (the project-ellipsoid $area, area($geometry), a custom sphere) has an exact sf partner, and qgis_process without an ellipsoid returns the flat area of the layer.
  • QGIS NULL and R NA: what survives the trip - a QGIS filter treats NULL as false like dplyr, bare [ indexing adds rows of NA, and a CSV export merges NULL with empty text where a GeoPackage keeps them apart.
  • Natural breaks in QGIS and R: Jenks on large layers - which QGIS classification modes match classInt, why Natural Breaks can differ even on a small layer, and why above 30009 features it classifies phantom zeros.
  • Reprojecting a raster in QGIS and R: opposite defaults - QGIS Warp copies the nearest cell while terra project() interpolates unless the raster has a category table, so a land-cover map gains invented classes along its boundaries and a nearest-neighbour DEM leaves seams in slope.
  • Georeferencing RMS is not accuracy - the Georeferencer reports the residual at its own control points, so it falls as the transformation is given more freedom and reads exactly zero for a spline that is still metres out between the marks.
  • Spatial autocorrelation and Moran’s I - testing for spatial dependence with spdep.
  • Kriging and spatial interpolation - continuous surfaces from scattered point samples.
  • The variogram and the GP kernel - the term by term dictionary between geostatistics and Gaussian processes, and the one place the two estimators part company.
  • Separable space-time covariance, tested - a product of a spatial and a temporal correlation factorises through a Kronecker product, but it fixes one spatial range at every time lag, and fitted to a non-separable truth it understates the cross-covariance.
  • Stream networks and tail-up covariance - interpolating along running water, where the Gaussian covariance stops being a valid one and a tail-up model is built from a moving average so that it cannot fail.
  • Conditional simulation versus kriging - the kriged map is the best guess cell by cell and therefore too smooth for the area above a threshold, the peak or the patch count; conditional simulations get those right at the price of pointwise error.
  • Spatial cross-validation when the target is a map - block folds overstate a random sample’s map error and random folds understate a clustered one’s; compare two distance distributions before drawing any fold.
  • Geographical detector: the interaction rule - q is eta squared and fine as a description, but the interaction verdict follows sample size, the sign of the driver correlation and autocorrelation rather than interaction; neither toroidal shift test on a raster held its level in every design tried.

Satellite time series

A raster stack of dates is a set of time series stored in a map’s shape. These four build the cube, fit a seasonal curve to every pixel, deal with the cloud, and audit the covariate that comes out the other end.

  • NDVI time series from a raster stack - the layer axis rather than the map, the recycling trap that silently returns hundreds of layers, and why the raw date of peak greenness is worse than a fitted one.
  • Harmonic regression on a seasonal raster - amplitude and phase per pixel from a linear model, how many harmonics to keep, and the phase branch cut that makes averaging peak dates as numbers wrong.
  • Filling cloud gaps in a satellite series - cloud is contiguous and seasonal rather than random, the ranking of fillers changes with the quantity you want, and the observations that pass the mask do more damage than the ones it removes.
  • Checking a remote sensing covariate - alignment, extraction rule, grain, timing and the fact that the covariate is an estimate the model treats as known.

Species distribution modelling

Predict where a species can occur from occurrence records and environmental layers.

Presence-only distribution models

Most occurrence data are presence-only: records of where somebody saw the species, with no matching record of where nobody did. MaxEnt is the usual tool, and it is a penalised Poisson point process wearing a different name. These four tutorials build it from scratch, so the settings stop being folklore.

Macroecological patterns

Patterns that only appear once many species are on one graph, and the measurement decisions that produce most of what you see.

  • The abundance-occupancy relationship - occupancy is a censored measure of abundance, so a strong positive relationship appears with no biology at all in the generating model, and the scatter around it reads out spatial aggregation.
  • Range size distributions - the right skew comes out of almost any multiplicative process, and grain and record count move the small-range tail further than anything ecological in the data.
  • Rapoport’s rule and the Stevens method - Stevens band means invent the rule wherever richness peaks, pole clipping biases species midpoints too, and dropping edge-touching species makes the false rule more frequent.
  • The mid-domain effect as a null for richness - a central environmental hump fits the range-shuffling null with r-squared near 0.9; the envelope share, ranked among the null placements, and a species midpoint test tell geometry apart.
  • Extrapolating a species-area curve beyond the plots - a power law from small plots wins on AIC and misses larger areas by a factor set by aggregation and pool saturation; run backwards, its overshoot of the species lost at once is largest when little habitat is lost.
  • Checking a macroecological pattern - the shared denominator, the random-placement null, species that are not independent points, and a slope that moves with grain and extent.

Niche overlap between species

Put a number on how far two species share their environment, test it against a null, and see how much of that number belongs to the landscape rather than the species.

  • Niche overlap: Schoener’s D and Warren’s I - the two density-comparison metrics behind ENMTools and ecospat, built from first principles, and why I sits above D for the same pair.
  • Niche equivalency and similarity tests - two permutation tests with two different null hypotheses, and why a rejected equivalency test is not evidence of ecological difference.
  • Niche overlap and the background - hold both species fixed, change only what climates the region contains, and watch the measured overlap slide; plus the correction and its price.
  • Checking a niche comparison - three checks: the smoothing bandwidth moves the answer more than sampling does, low overlap can be geography, and the test can disagree with itself.

Detection and occupancy

Presence data are incomplete because species get missed. These models separate detection from occupancy.

Dynamic occupancy

Occupancy across several seasons, where sites are colonised and go locally extinct, and detection is still imperfect.

Occupancy variants

Three models that promise more than occupancy from the same detection table, each resting on an assumption the table cannot test.

eDNA and molecular detection

A water sample is a detection method with its own hierarchy: the species has to be at the site, its DNA has to be in the bottle, and the PCR replicate has to amplify. These add the laboratory layer to the occupancy models above, and take seriously the two errors it brings.

Acoustic monitoring

An autonomous recorder and a species recogniser turn a field season into a table of timestamped detections with confidence scores attached. That table is not a table of counts, and the difference matters before any model is fitted.

Abundance and density estimation

Go beyond presence to count: estimate abundance and density from unmarked animals, while correcting for the individuals nobody saw.

  • Removal and depletion sampling - estimating a closed population from declining catches.
  • Removal estimates when catchability falls - a per-pass fall in catchability drags the Zippin estimate low and its interval off the truth, a fit test with three passes barely notices, more passes do not help, and a release of marked fish adds the missing information.
  • Declaring eradication after empty traps - a run of empty sessions sized from the removal capture rate is calibrated when every animal is equally catchable, but removal leaves the least catchable animals behind, and under strong heterogeneity neither extra sessions nor a heterogeneity model makes a declaration trustworthy.
  • Time-removal point counts and observer arrival - song suppressed by the observer’s arrival pushes a time-removal estimate high for rare singers; the one-minute fit test sees it best where it matters least, and a settling period pays only up to a break-even departure rate that shifts with singing rate, reaction strength and when birds leave.
  • Removal passes until the catch drops - stopping once a pass catches half the first trims the high tail of the removal estimate but leans it low, and its interval covers the truth less often at low catch probability.
  • N-mixture models for abundance - abundance from repeated counts without marking individuals.
  • N-mixture reliability and the detection trade-off - the three ways an N-mixture abundance estimate can be unreliable without the count warning you.
  • Checking an N-mixture model - goodness of fit, residuals and K-sensitivity, and why passing is necessary but not sufficient.
  • Open N-mixture models and the detection trap - survival and recruitment from repeat counts with a hand-built forward algorithm: the repeat visits catch a drift in detection once detection may vary by year, while detection that falls with abundance pushes both rates off until a detection-on-abundance model of the right shape is fitted.
  • Disturbed animals in repeated counts - when counting makes an animal harder to count again, the N-mixture and removal models both run high from opposite ends, a count-only Mb model with the number already counted recovers abundance, and with two visits nothing can tell it from a time effect.
  • Change-in-ratio population estimates in R - population size from a sex ratio before and after a known harvest: the error grows as the ratio change shrinks, the median drifts once the change can flip sign, and a profile interval can have no upper end.
  • Pitfall catches and the depletion zone - a removing trap in a random walk: the depletion zone bends the effort offset only a little, walking speed raises catches mostly through the encounter formula, and diffusion sets how much local density is left.
  • Detection from a single drone flight - one pass gives one count per tile, so abundance and detection separate only through the curvature of the detection link: distinct covariates with a steep slope recover the total, a covariate shared with density widens the abundance band by a factor of 124, and a second flight cuts the detection standard error by 13.

Distance sampling extensions

The base method first, then covariates, points instead of lines, and a hierarchical version. Each extension moves the single number the density estimator reads off the curve at zero.

Camera trap density

Density from animals nobody marked: the gas model, the speed it needs, and the way round needing it.

Closed capture-recapture

Mark a sample, look again, and read population size off the overlap. What decides whether that works is the failure of the closed-population assumptions, not the arithmetic.

Spatial capture-recapture

Estimate density directly by modelling where each individual lives, not just how many were seen.

Multi-state capture-recapture

Marked individuals move between states or sites between captures, and state-specific detection can masquerade as movement.

Open-population abundance

Survival, recruitment and abundance from the same capture histories, with three levels of exposure to the one assumption you cannot test.

Community and multi-species models

Model a whole assemblage at once: share information across species so the rare ones borrow strength from the common, and account for the species that were never detected.

Integrated and multi-scale models

Join data of different kinds, or model a process at more than one spatial scale, in a single likelihood that no single data set could support on its own.

Spatial point patterns

Treat the locations themselves as the data: are events clustered, regular or random?

Movement and space use

Follow individuals rather than sites: where an animal ranges, how it moves, and which habitat it selects.

State-space models for movement

Separate the animal’s true path from observation error, and say how much the data can resolve.

Step selection

Ask what an animal chooses from what was available to it, step by step.

Population dynamics and matrix models

Project a population forward from its vital rates, and find which rates matter most.

Integral projection models

The continuous-size successor to matrix models: a kernel built from vital-rate regressions, with no need to bin individuals into stages.

Integrated population models

Join counts, capture-recapture and productivity in one likelihood to estimate demographic rates that no single data set identifies.

Survival and time-to-event

Estimate how long individuals live from censored, known-fate or recapture data, correcting the bias in a naive mean.

Survival extensions

Go beyond a single event and proportional hazards: competing causes, parametric models, dependence between times, and how to check the fit.

Population time series

Infer process from a run of annual counts: density dependence, hidden state, trend shape and the form of regulation.

Exact stochastic simulation

Populations change by whole animals, one event at a time. These posts build the sampler that reproduces that exactly, and measure what every shortcut costs.

Fisheries stock assessment

An assessment turns a catch record and an abundance index into a number a manager acts on. The arithmetic is population dynamics with removals, and most of the difficulty is that the data constrain the answer far less than the output suggests.

  • Surplus production models in R - a biomass dynamics model fitted to catch and an index, the reference points that come out of it, and why a stock that only ever declined cannot separate growth rate from carrying capacity.
  • Stock-recruitment and reference points - Beverton-Holt and Ricker in terms of steepness, per-recruit arithmetic, and a target that moves with an assumption the data barely constrain.
  • Standardising catch per unit effort - removing fleet and season effects from an abundance index, the prediction step people get wrong, and the hyperstability no model can standardise away.
  • Checking a stock assessment - the retrospective pattern, contrast as a check you can run before fitting, the price of assumed parameters, and harvest control rules under estimation error.
  • Reconstructing a population from ages at harvest - cohort analysis returns the guessed harvest rate as the present-year population, the age likelihood at constant effort is an exact ridge, and known effort contrast identifies the rate unless catchability creeps.
  • Fishing, age truncation and spawning variability - fishing old fish raises the CV of spawning output by a closed-form filter and flattens its spectrum, but a fifty-year index often misses the change and the naive variance test is oversized.
  • Borrowed age-length keys and strong year classes - a key carried from another year halves a strong year class; the inverse EM key with a fitted growth curve recovers it, except where older ages overlap in length.
  • Trawl selectivity when hauls differ - a covered-codend L50 fitted to pooled hauls covers the truth less than half the time once hauls differ by a centimetre, quasi-binomial does not see it, and the haul is the replicate.
  • Gill-net selectivity and the fish it cannot see - a three-mesh series stops fishing right at the size the report is about, so the SELECT correction returns less than half of the large-fish share whichever family is fitted, and the repair is a fourth mesh rather than a better model.
  • Earlier maturation: evolution or faster growth? - the age at maturity falls under faster growth alone; the PMRN midpoint does not, but at 100 fish per age it finds a real shift in the rule in fewer than six series of ten.

Plant and animal phenology

Turn field dates into timing you can analyse, and watch how sampling effort, not the season, can drive an apparent shift.

  • Phenology in R: day of year and event timing - convert field dates to day of year, treat a season as a distribution rather than a single date, and use circular statistics when timing wraps around the year.
  • First flowering dates and sampling effort - why the first date advances as monitoring effort grows while the mean and median stay put, the extreme-value bias behind spurious phenological shifts.
  • Phenological trends and temperature - estimate sensitivity to spring temperature, and see how rising effort in warm years inflates the first-date trend while the mean date holds.
  • Quantifying phenological mismatch - warming that closes the gap between peak demand and peak food can leave consumers hungrier, and the trend in a difference is the weakest series in the study.
  • Checking a phenology analysis - three checks: does the estimate survive thinning, is the season censored by the survey window, and do the summaries agree on the trend.
  • Daylength as a predictor in ecology - compute photoperiod in base R, see why it cannot beat day of year at one site, and why the latitude design that identifies it also confounds it.
  • Curve registration and functional PCA - the day by day mean of shifted seasonal curves is too low and too wide, and whether registration is a shift or a pinned warp decides what a functional PCA calls amplitude.
  • Chilling, forcing and projected leaf-out - a forcing-only degree day model overstates the spring advance under warming and misses the delay where winter chill runs out; the chill rule decides the projection.

Climate covariates

Turning a weather record into the variable an ecological model actually needs, and measuring how much of the answer the construction decides.

  • Degree days and thermal time in R - three routine ways to accumulate thermal time from daily extremes, and why the assumed base temperature moves the predicted date further than warming does.
  • Drought indices for ecologists - a water balance, the standardised precipitation index and its evapotranspiration cousin by hand, and how the accumulation window and the baseline period decide which years count as drought.
  • Climate window analysis in R - searching every window for the best climate predictor, the false positive rate that search produces on pure noise, and the randomisation null that repairs it.
  • Checking a climate window analysis - shared trends, competing climate variables, held-out years, and a window that is statistically sound and biologically wrong.
  • Distributed lag models versus the climate window - a smooth lag weight fitted as an mgcv linear functional term: the searched window’s median slope sits near the total while its interval undercovers, the distributed lag interval stays near 95 per cent, and thirty years usually miss the peak lag.
  • Reset time and the double-counted hot day - a min-max thermometer read in the afternoon carries a warm evening into the next day, inflating mean maxima and hot days, and a monthly correction fixes the mean but not the count.
  • Heatwave counts: persistence, rule order, warming - the Hobday heatwave rules in base R: at the same share of hot days the count is set by persistence and by whether short runs are dropped before gaps are joined, and under warming it peaks and falls while heatwave days keep rising.

Climate velocity and range shifts

How fast the climate moves across the ground, how fast species follow, and how much of the measured gap between the two is measurement.

  • Climate velocity in R - the local temporal trend over the local spatial gradient, built from the arithmetic up, and why the map is largely terrain and the mean is largely a flooring rule.
  • Range shifts and the climate lag - four ways to define a range edge, the bias each one carries when survey effort changes, and what that leaves of an estimated climatic debt.
  • Checking a range shift analysis - resurvey effort, the null distribution of a shift, elevation against latitude, and the community temperature index taken apart.

Species competition and coexistence

Fit competition coefficients from a field experiment, turn them into coexistence quantities, and see how far past the data the verdict actually reaches.

  • Fitting annual plant competition models - fit Beverton-Holt competition coefficients from a response-surface experiment, and why an additive design cannot identify self-limitation.
  • Niche and fitness differences - turn fitted coefficients into a niche difference and a fitness ratio, and see why the stronger competitor need not exclude its rival.
  • Assumptions behind coexistence - the invasion verdict is an extrapolation far beyond the data; how model form and germination rates decide it where no data reach.
  • Checking a coexistence analysis - three checks: mutual invasibility over time, whether the design identifies self-limitation, and stability of the verdict to model form.

Seed and propagule dispersal

Fit the density that describes where offspring land, and treat the far tail with the suspicion it deserves, because that is the part that sets spread and connectivity.

  • Fitting dispersal kernels in R - seed-trap distances are not the location kernel, and the missing ring-area factor doubles the fitted scale if you ignore the geometry.
  • Fat-tailed dispersal kernels - several families fit the same seed rain and agree on the bulk while disagreeing by orders of magnitude about long-distance dispersal.
  • The mean dispersal distance - the mean averages over a tail no trap ever sampled, is weakly identified, and for some fitted kernels does not exist at all.
  • Checking a dispersal kernel - three checks: how much the tail rests on a few seeds, whether the trap window truncates it, and whether the answer survives a change of family.
  • Misread rings and the dispersal tail - misread ring numbers link recoveries to the wrong site and fake a fat tail; a mixture with a null built from the ring register recovers the kernel.
  • Seed dispersal: the nearest adult is not the parent - nearest-adult distances are capped by the tree spacing, a closed form in kappa; the inverse seed-trap model fails at wide kernels unless more seeds are caught.

Invasion spread

How fast a population moves across a landscape, and what decides whether a single speed exists at all.

  • The speed of an invasion front - the asymptotic speed in closed form from the moment generating function, checked against a simulated front, and why a handful of individuals at the leading edge set it.
  • Fat tails and accelerating spread - a fat-tailed kernel has no asymptotic speed at all, so the front accelerates, and two kernels the seed data cannot separate diverge by a multiple inside one forecast.
  • Long-distance jumps and stratified spread - rare jumps found colonies that spread in turn, which multiplies the mean speed and multiplies the spread of the forecast much harder.
  • Checking an invasion spread model - the front definition, a lag that detection delay imitates exactly, and the Allee effect that breaks the linearised speed formula.
  • Critical patch size and the dispersal kernel - the kernel eigenvalue sets the minimum patch; at equal variance a peaked kernel needs less habitat and also spreads faster, and demographic noise lifts the practical threshold, much less under a ceiling than under Beverton-Holt.
  • Spatial sorting: the front that breeds its speed - a heritable dispersal trait accelerates a Gaussian front and widens the spread between replicates, and only the front to core trait cline separates it from a fat-tailed kernel.

Metapopulation dynamics

Colonisation and extinction across a patch network: the classic model, fitting it from one snapshot, and the single number that ranks a landscape for persistence.

  • The Levins metapopulation model - colonisation and extinction in a single equation; why the occupied fraction settles below one and equals one minus the extinction to colonisation ratio.
  • The incidence function model - fit colonisation and extinction from a single occupancy snapshot with no turnover data; area proxies extinction, connectivity proxies colonisation.
  • Metapopulation capacity - the leading eigenvalue of the landscape matrix as one number that ranks landscapes for persistence.
  • Checking a metapopulation model - three checks: a transient snapshot hides the area to extinction signal, alpha is weakly identified, and stochastic extinction rises at narrow margins.

Bayesian computation

Build the machinery of Bayesian inference by hand, and read the diagnostics that tell you it worked.

Gradient samplers and approximations

What Stan is doing, why a hierarchical model can sample badly without being wrong, and how to tell that the computation returned the posterior you asked for.

Bayesian latent-state models

The same latent-variable move applied to classic ecological models, sampling the hidden quantity directly.

Inference without a likelihood

Some models are simple to simulate and hopeless to write a likelihood for. Approximate Bayesian computation fits them anyway, by comparing simulated data with the data you have.

Stable isotope mixing models

Work out what a consumer ate from its isotopes: the mixing geometry, a Bayesian fit by hand, and the assumptions that move the answer more than the data.

Isotopic niche

The same isotope values read as a niche rather than a diet: how wide a group’s isotopic space is, where it sits on the food chain, and how far two groups overlap.

  • Isotopic niche width: hulls and ellipses - the convex hull area grows with sample size without bound while the corrected standard ellipse does not, so unequal samples decide a hull comparison.
  • Trophic position from stable isotopes - trophic level from nitrogen, the baseline it is measured against, and why the assumed discrimination factor carries most of the error high up the chain.
  • Isotopic niche overlap between groups - ellipse overlap is asymmetric and depends on the containment probability you pick, and two consumers with no shared prey can overlap completely.
  • Checking an isotopic niche analysis - sample size and power, lipid correction, the pipeline decisions that change the verdict, and what tissue turnover does to a comparison.

DNA metabarcoding

A metabarcoding run returns a table of read counts whose row totals were set by the sequencer. Between the animal that ate something and that table sit DNA extraction, amplification, index assignment and a filtering decision, and each of them leaves a measurable mark.

  • Metabarcoding reads as compositional data - relative read abundance and frequency of occurrence answer different questions and fail in different ways, and the detection threshold decides which taxa exist.
  • PCR bias and amplification efficiency - why a small per-cycle difference becomes a large error, why the log-ratio is the right scale, and what a mock community can and cannot correct.
  • Contamination filtering in metabarcoding - three sources with three different signatures, four filtering rules scored against each other, and a rule that classifies better but analyses worse.
  • Checking a metabarcoding analysis - rarefying against the alternatives, the bloom that makes every other taxon fall, PCR replicates that are not replicates, and the read depth a diet needs.
  • Dirichlet-multinomial models for read counts - a multinomial interval ignores the variation between samples and collapses as depth grows, the Dirichlet-multinomial caps the effective depth, and more samples help where more reads do not.
  • Pseudocounts turn read depth into a result - a fixed 0.5 makes a sparse taxon’s log-ratio a function of library size, so unequal depth is reported as a group effect, while rarefying first or a negative binomial with a log depth offset holds the nominal rate.

Meta-analysis

Pool effect sizes across studies, measure how much they disagree, and check whether the published record is a fair sample.

  • Random-effects meta-analysis - Hedges’ g, DerSimonian-Laird and REML tau-squared, forest plots and coverage.
  • Heterogeneity in meta-analysis - Cochran’s Q, I-squared with an interval, and a prediction interval for a new study.
  • Meta-regression with moderators - explaining heterogeneity with a study-level moderator, and keeping the error rate honest.
  • Dependent effect sizes in meta-analysis - several effects from one study are correlated, the naive standard errors are too small, and a three-level model puts the study back in.
  • Phylogeny in a multi-species meta-analysis - ignoring the tree shrinks the pooled interval by plain arithmetic; the correct model still undercovers, worst when its phylogenetic variance lands on zero, and a t on the tree’s effective species count covers on average, conservatively.
  • Checking for publication bias - funnel plots, Egger’s regression and trim-and-fill, with the limits of each.
  • Selection models for publication bias - fitting the selection mechanism by maximum likelihood instead of patching the funnel afterwards, and measuring how many studies it takes before that pays.
  • Effect sizes from incomplete reports - recovering a standard deviation from a median and quartiles before the pooling starts, and what a standard error read as a standard deviation does to the weights.
  • Meta-analysis of little-replicated experiments - with three bottles per arm the variance of a log response ratio is an estimate too: fixed-effect coverage falls as studies are added, tau-squared is manufactured, and Egger’s test fires on an honest literature.
  • Inclusion criteria move the pooled effect - a screening rule that tracks a moderator shifts the pooled effect while the funnel plot, Egger’s test and I-squared stay quiet, and a sweep over defensible rules is wider than the noise alone.
  • Checking published summary statistics - GRIM, standard deviation bounds and p values recomputed from a rounded t: a rounded number is a band, the checks go blind at larger samples, and one unreported exclusion flags an honest mean.
  • Prediction intervals for a new site in meta-analysis - how often the prediction interval covers a new site’s effect: conservative with five studies, short of nominal from twenty on once tau-squared is often estimated as zero, and no estimator swap repairs it.
  • PET-PEESE and publication bias under heterogeneity - the regression correction fails on a significance filter once studies differ by site, repairs reporting of the best of several responses on a common scale, and Egger’s test rarely asks for it.
  • Year trends in effect sizes and the SE covariate - growing sample sizes plus a publication filter fake a decline with publication year; a standard error covariate removes it but costs much of the power to see a real decline, and the g-based standard error drags real declines towards zero.
  • Correlations from gradients of different length - studies with one slope but gradients of different length give heterogeneous correlations and a spurious extent moderator; slopes, a log SD(x) moderator or a variance-adjusted range correction remove it.

Structural equation models

Write down a causal diagram and fit it equation by equation: split an effect into direct and indirect paths, then test the structure itself.

Causal inference

Estimate a causal effect from observed data by choosing what to adjust for on purpose, and check the one assumption you cannot test.

Panel and comparative case studies

Estimate an effect from repeated observations across units and time, when a clean control group is not available.

Measurement error

What error in a predictor or response does to an estimate, and what it takes to correct for it, including the chronological and calibration error that reconstructions carry.

Missing data

Why the reason data are missing matters more than how much, and how to analyse what is left honestly.

Compositional data

When counts only make sense as proportions, ordinary correlation and distance mislead; log-ratios put the analysis back on firm ground.

Multiple testing and error rates

Testing many hypotheses at once inflates false positives; controlling the error rate is a choice with real power costs.

Designing a survey

Choose where and how to sample so the estimate is unbiased and its variance is known, before any data are collected.

Monitoring design

Design a repeated survey to detect change over time, and know in advance whether it can. The second half of the section is the other half of the problem: a series only measures change if it stays comparable with itself while the taxonomy, the method and the recording effort all move under it.

Designing the repeat

Keeping the series comparable

  • Taxonomic revision and species trends - a split and a lump partway through a long series manufacture a richness trend in a community that never changed.
  • The price of harmonising a species list - putting two recording eras onto one backbone hides opposite trends, costs richness and drops records in a silent trait join.
  • How long a calibration overlap do you need? - what a season of running both methods side by side buys in trend precision, how that compares with spending the same effort on more survey years, and which sites to dual-run.
  • Testing a monitoring series every year - re-running the trend test as the series grows inflates the false alarm rate several times over, the first false alarm arrives early, and the estimate at stopping is steeper than the truth.
  • Detecting a die-off from carcass reports - a historical-limits alarm on weekly carcass reports: the variance model sets its real false alarm rate, and it helps detection only when the dispersion varies widely between weeks.
  • CUSUM for die-offs when reporting effort persists - a CUSUM and a single-week historical-limits alarm on weekly carcass reports compared at matched false alarm rates: once reporting effort persists from week to week the single-week rule finds a fortnight die-off more often, while a CUSUM stays level or ahead for a die-off spread over four weeks.
  • Combining species trends into one index - the arithmetic mean of species indices climbs out of nothing, from spread among species and from small counts alike, and the geometric mean does not.
  • Observer effects and the first-year dip - an observer term in a route count trend turns each novice first year into a spurious increase, one first-year indicator removes it, and a route-only trend stays nearly unbiased only when it starts with the survey.

Opportunistic records and citizen science

Getting a trend out of records nobody designed, by modelling the effort that produced them rather than pretending it was constant.

  • List-length analysis for opportunistic data - the length of a species list as a proxy for effort, two naive estimators that fail in opposite directions, and how much of the true trend is even reachable.
  • Reporting rates and effort drift - a scheme that modernises while the species stays put produces a large false trend, and four kinds of drift ranked by how much damage each one does.
  • Occupancy from unstructured records - building repeat visits out of a record stream, and why splitting one visit into two costs more than merging two into one.
  • Checking an unstructured-data analysis - spatial and temporal bias needing different corrections, taxonomic reporting bias, the first-record trap, and validation against a structured survey.
  • Multilevel post-stratification of records - records leave the remote cells of the frame empty, dropping them biases the estimate, the plug-in interval fails at thin effort, and a cell random effect in mgcv fills the gaps.
  • Revisits triggered by sightings in occupancy data - extra visits pulled in by recorded sightings leave occupancy unbiased, visits led by what locals know inflate it, the timing of the revisits rather than model fit is the clue, and a visit-count model repairs it only if it is right about empty sites.
  • Year lists: cut at the recorder, not the site - a recorder who logs each species once a year biases occupancy with a sign set by how many sites they cover, cutting each site at its first report fails once recorders cover several sites, and cutting each year-lister at their first report anywhere repairs it.
  • Flight-season shifts and false occupancy trends - a season sliding towards the edge of a fixed recording window reads as an occupancy decline; a year term on detection misses it once visits bunch, and a moving date curve recovers it.

Stratified sampling

Split a heterogeneous population into strata to sample each efficiently, then combine.

Adaptive sampling

Let the data guide where to sample next when the target is rare and clustered.

Checking the data against the design

A field season rarely returns exactly what the design specified, and nothing in a residual plot reports the difference. These measure what each gap costs, and the last one collects the checks that find them. Data provenance checks in R is the topic page for this section, with the species-list and unstructured-record cases from elsewhere on this page brought in alongside.

  • Non-response and site substitution - the crew reaches fewer plots than were drawn and walks to the nearest reachable one instead, and what that replacement rule does to bias and interval coverage.
  • Harvest surveys and the late respondent - extrapolating across reminder waves removes a share of the respondent bias that the returned forms cannot reveal; a random follow-up of non-respondents is the only repair whose bias does not rest on the unseen, and at equal cost a fourth mailing ties it in two frames.
  • Splicing a monitoring series - a change of method partway through reads as a trend, no ordinary diagnostic fires, and an era indicator recovers the real slope with no calibration data at all.
  • Rounded and coarsened measurements - a known recording grid adds variance and makes a normality test reject the ruler rather than the biology, and an interval-censored likelihood puts both back.
  • Values below the detection limit in R - substituting half the limit fabricates a trend when the laboratory improves, and the censored likelihood does not.
  • Digit preference and heaping in field data - rounding that leans towards the round numbers moves the mean, and heaping that differs between two arms manufactures a contrast where there is none.
  • Baseline selection and the return to the mean - targeting the worst sites returns a confident gain from a treatment that did nothing, while every pre-trend diagnostic stays quiet.
  • Checking your data against the design - five checks that compare the returned data with the frame, the protocol dates, the recording grid, the allocation and the code list, each with the case it cannot see.
  • Data entry errors and what your checks catch - a range rule catches a third of keying errors and double entry nearly all, yet the errors each leaves behind decide how far the treatment contrast moves, and a higher catch rate can leave it further off.
  • Spike tests on logger data delete real peaks - a running-median spike test is clean at a 5-minute interval but deletes about half the storm surge peaks at hourly logging, because surge width counted in readings, against the threshold, decides it by geometry.
  • Instrument drift, run order and check standards - a sorted analyser run turns drift into a treatment effect, check standards leave their own reading error behind, and interspersed order removes both.

Allometry and scaling

Fit and compare scaling exponents on log-log axes, where the choice of line matters.

Species associations and joint models

Model a whole community at once and ask what fitting them together adds.

Biodiversity and ecosystem function

How diversity changes what a community does, and how to partition the effect.

Litter decomposition and carbon

Turning mass remaining in a litterbag into a decay constant, and then into a carbon flux, without losing track of what each step assumed.

  • Fitting litter decomposition curves - the single exponential fitted two ways, why the assumed error structure changes the answer, and how much of a decay constant is set by the length of the study.
  • The recalcitrant pool and the asymptote - the two-pool and asymptotic models are close to indistinguishable on a real harvest schedule, and the schedule is worth more than extra bags.
  • Mass loss and the carbon budget - carbon concentration drift, soil in the bags and fragment loss, and what the reciprocal of a decay constant does to a steady-state stock.
  • Soil carbon stocks and equivalent soil mass - sampling both treatments to the same depth gives the denser soil more soil to hold carbon in, and the equivalent soil mass correction takes the invented difference back out.
  • Checking a decomposition analysis - bags nested in plots, comparing treatments on the right scale, the fixed starting mass, and the number that lies outside the data.

Ecosystem carbon flux

A flux tower measures net exchange every half hour, and the annual budget that gets published is the output of a screening rule, a gap fill and a partitioning model. These five measure what each step decides, and a sixth takes the same question to a stream.

  • Night-time flux and the u-star threshold - calm nights lose respired carbon before it reaches the sensor, the screening threshold is estimated rather than known, and its uncertainty carries into the annual sum.
  • Gap filling a flux time series - the holes are not random, so the damage comes from the mechanism rather than the amount, and only look-alike matching reaches the noise floor.
  • Partitioning net flux into GPP and respiration - the two gross fluxes are model output, their errors are correlated, and net exchange stays right while both move together.
  • Stream metabolism from one oxygen logger - the aquatic counterpart, where depth and reaeration decide whether a day’s production estimate is a number or noise.
  • Where the night-time flux comes from - the source area stretches upwind on stable nights, so the u-star screen selects on ground as well as on time, and the sign of that selection comes from the site’s own coupling between turbulence and stability.
  • Checking an annual flux budget - six checks on a published sink: threshold uncertainty, the carbon share of filled half hours, night-biased gaps, what the error bar contains, and a defensible-choices multiverse.
  • Net primary production from repeated harvests - the destructive-harvest route to production: summed increments grow with the number of harvest dates from noise alone, the peak misses turnover, and agreement with the truth is two errors cancelling.
  • Chamber fluxes: linear or exponential fits - the soil chamber measurement: the linear slope’s bias is a formula, four syringe samples leave the exponential fit scattered with a long upper tail, and an AIC rule between the two mostly lands in between.
  • Sap flow and the zero-flow baseline - the zero-flow baseline of a thermal dissipation probe turns night transpiration into lost water use and probe noise into extra, and averaging the predawn readings before taking a maximum removes most of the noise part.

Thermal performance and physiology

How performance depends on temperature, and what a variable climate does to it.

Optimal foraging

What an animal should eat and where it should feed, and how to test it.

Allee effects and small populations

Positive density dependence at low numbers, and the threshold it creates.

Life-history strategies

How selection shapes the timing of reproduction in a variable world.

Source-sink dynamics

How movement between good and bad habitat sets where a population persists.

Habitat selection and the ideal free distribution

Where animals settle when they compete for patchy resources.

Evolutionary quantitative genetics

How selection on measured traits becomes evolutionary change across generations.

This section and the animal model section below are also available as a free book, rewritten as one continuous text with a single notation: Quantitative Genetics from Scratch in R.

The animal model

Heritability estimated from a pedigree rather than from a selection experiment, with the machinery written out by hand.

Repeatability and individual variation

How much of the variation sits among individuals rather than within them, and what that number depends on.

Evolutionary game theory

What happens when the payoff to a behaviour depends on what everyone else does.

Kin selection and social evolution

Why helping a relative can pay, and the exact accounting behind it.

The evolution of cooperation

How cooperation survives a game that defection wins on its own.

Indirect reciprocity and reputation

Cooperation among strangers, when third parties know what you did.

Network reciprocity and spatial games

What changes when neighbours interact instead of a well-mixed crowd. The arc runs from clustering on a lattice, to the replacement rule that decides whether the benefit-to-cost condition holds at all, to the Price equation split that says where the sign flips, and ends with the conventions a spatial result quietly rests on.

Finite populations and gradual evolution

Selection is not the only thing moving once the population is small. These four build drift and fixation from the birth-death step up: the exact fixation probability of a single mutant, the thresholds that replace the ESS when chance matters, the branching point where one lineage becomes two, and how many replicates a fixation estimate needs before it means anything.

Population genetics

Allele frequencies carry their own record of drift, gene flow and sampling error. These four start from one locus in one population and end with the checks that decide whether a differentiation estimate means anything.

Effective population size

The rate at which a population loses diversity depends on how it breeds, not on how many adults get counted. These four define that rate, estimate it from markers, and test what a crash leaves behind.

Coalescent theory and sequence diversity

Run drift backwards and the sample’s ancestry becomes the object of study. These four build gene trees, put mutations on them, and turn the resulting patterns into statistics with known failure modes.

Genetic clustering and assignment

The bar plot that appears in nearly every population genetics paper, built from scratch: what the model actually says, why the number of clusters is a model choice rather than a count, and the narrower question that has a measurable error rate.

Landscape connectivity

Habitat pattern and movement cost, with every algorithm written out in base R rather than called from a GIS package. These four go from describing the pattern to testing whether a connectivity map means anything.

Landscape genetics

Genetic differentiation as the response variable and the map as the predictor. These take the resistance surfaces of the previous section and ask whether the genetic data support them, together with the inference problem that pairwise data creates.

Conservation prioritisation

Turning biodiversity data into a plan: which sites, at what cost, in what shape, and how much of the answer was decided before the algorithm ran.

Reintroduction and restoration

Putting a population back, and measuring whether a site has recovered: allocation under a fixed number of animals, reserve configuration, and recovery measured against a moving target.

  • Reintroduction release strategies - how to spend a fixed number of animals across years and stages, where the marginal animal stops paying, and the habitat problem no schedule can fix.
  • SLOSS and reserve configuration - single large or several small, answered twice: by the beta diversity of the pool for richness, and by the spatial correlation of bad years for persistence.
  • Restoration trajectories and recovery - the metric, the reference and the chronosequence each give a different recovery percentage, and a truncated series cannot see the asymptote.
  • Checking a reintroduction analysis - the projection horizon, which uncertainty dominates, correlated vital rates, and a density dependence assumption a short series cannot test.

Decision analysis for conservation

Making the choice explicit: objectives and weights, what it is worth to reduce uncertainty first, and managing a system while still learning how it works.

  • Structured decision making in R - a consequence table, dominance screening that needs no weights at all, swing weighting, and the normalisation choice that quietly changes the winner.
  • The expected value of information - uncertainty that does not change the best action is worth nothing to resolve, and the survey accuracy below which no amount of data helps.
  • Adaptive management and learning - model weights updated from outcomes, the action that pays best being the one that teaches least, and the horizon beyond which learning is worth its cost.
  • Eliciting probabilities from experts - the four-point question, how far a stated ninety per cent interval falls below nominal, and the pooling rule the combined number quietly depends on.
  • When decision makers disagree - four sensible aggregation rules on one agreed consequence table, three different winners, and what the compromise that avoids choosing costs.
  • Checking a decision analysis - how firm the recommendation is, whether the uncertainty matters, what a new alternative does, and how risk attitude reorders everything.

Sequential decisions in management

When today’s action changes tomorrow’s state, the answer stops being a single choice and becomes a rule: what to do in each state the system can reach.

  • Markov decision processes for management - value iteration over a dynamic state, why the output is a policy rather than a decision, and a rule that holds still while its own reported value moves.
  • Stochastic dynamic programming for harvest - deriving the escapement rule instead of comparing fixed ones, and why the shape of the payoff bends it where recruitment noise does not.
  • When to stop monitoring - monitoring as an optimal stopping problem, the price of surveying until significance, and the gap between statistical power and decision relevance.
  • Checking a sequential decision model - the discount rate, a state grid coarse enough to invent a permanent cure, an estimated transition matrix, and the end of the horizon.

Janzen-Connell and species coexistence

A mechanism that punishes a species for being common, in four steps: what it does to diversity, how it is measured on a single seedling, why it stabilises coexistence, and the confound that erases it.

Fluctuation-dependent coexistence

How a changing environment lets competitors coexist that a constant one would not.

Alternative stable states and tipping points

When a community has more than one outcome, and history or a slow driver decides.

Disease ecology and epidemics

How pathogens spread through host populations, and the thresholds that govern them.

Epidemic dynamics and estimation

Beyond the basic compartments: what latency does to the numbers you measure, how to get a reproduction number out of a case series, and why endemic disease returns in waves.

  • The SEIR model and the latent period - adding an exposed class leaves the reproduction number untouched and changes the growth rate, so a growth rate read through the wrong model gives the wrong answer.
  • Estimating R0 from incidence data - the exponential growth rate mapped through a generation interval, the renewal equation for a time-varying reproduction number, and why cumulative counts give false precision.
  • Prevalence from an imperfect test - apparent against true prevalence, the Rogan-Gladen correction, and what the validation study’s own uncertainty does to the interval.
  • Two imperfect tests and no gold standard - the Hui-Walter model fitted by maximum likelihood, why test dependence leaves no trace in the fit, and how a small prevalence gap leaves sensitivity unbounded.
  • Faecal egg count reduction tests at low counts - a McMaster factor of fifty usually makes a 99 per cent drug read 100 per cent, the paired bootstrap interval collapses, and a likelihood on the eggs actually counted does not.
  • Infection rates from pooled vector samples - the minimum infection rate against the pool MLE, the bias from pooling within trap-nights, and why randomised pools still give a too-narrow interval for the vector population.
  • Force of infection from age prevalence - the catalytic model as a cloglog GLM with a log age offset, and the two mechanisms one cross-section cannot separate.
  • Density or frequency transmission in enclosures - the transmission exponent as a cloglog GLM across group sizes, why a narrow range of group sizes cannot decide the form, and why the interval has to be computed across enclosures.
  • Snapshot prevalence and the phase of an epidemic - one PCR survey across sites reads each epidemic’s phase, so the density slope depends on survey date and introduction synchrony; serology from the same visit as the repair.
  • Seasonality and recurrent epidemics - the intrinsic damped oscillation, the forcing amplitude that turns an annual cycle biennial, and the community size below which the pathogen fades out.
  • Checking an epidemic estimate - four checks on the data rather than the model: reporting delay, time-varying under-reporting, weekly aggregation, and an assumption sweep priced against the model’s own interval.

Designing and exporting a figure

The design decisions inside a figure are measurable, and the wrong one costs the reader accuracy rather than taste. The last step, getting it out of R at the size and resolution a journal asks for, is part of the same job.

  • Choosing colours for ecological data - sequential, diverging and qualitative as a question about the data, the lightness inversions a rainbow ramp creates, and a colour vision check that ends in a number.
  • Designing an ordination figure - distance is the content, so the shape of the panel is part of the analysis, and the stress a two-dimensional map cannot show you.
  • Effect plots that show the data - what a bar of means hides, partial against marginal effects from one model, and what each of the three interval widths actually covers.
  • Publication-quality ggplot figures - physical size, resolution and clean export with ggsave.
  • Checking a figure - a truncated axis measured off the drawn scale, a title width checked against the panel from font metrics, colour vision loss, and the title read as a claim.

Common pitfalls

A few posts above are dedicated to mistakes that are easy to make and hard to spot. If something looks wrong, these are the ones to reread: pseudoreplication, common PERMANOVA mistakes, collinearity and VIF, when not to use Shannon, GLM residual diagnostics, offsets for rates and densities, comparing significance is not a test, and residuals as a variable.

Newsletter

Get new tutorials by email

New R and QGIS tutorials for ecologists, straight to your inbox. No spam; unsubscribe anytime.

By subscribing you agree to receive these emails and confirm your address once. See the privacy policy.