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 four measure what each habit catches and what it misses.

  • Testing your analysis code - a test runner in twenty lines of base R, and which kind of test earns its lines against thirty-odd deliberate bugs.
  • Debugging and defensive R code - silent recycling, the factor trap, and what stopifnot catches that a handler cannot.
  • Speeding up your analysis code - measure before you rewrite, why vectorising pays a constant and a hash lookup pays more and more, and when the slow readable version is right.
  • Checking an analysis script - does it run from a clean session, give the same answer twice, and report the numbers it actually computed.

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.

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.

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.

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.

Bootstrap and resampling inference

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

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.

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.

  • MaxEnt as a Poisson point process - the point process likelihood, the count GLM, the Gibbs solution and weighted logistic regression are one model, and only the level differs.
  • Regularisation and features in MaxEnt - hinge and threshold features built by hand, the L1 penalty that keeps them in check, and the regularisation path measured against held-out records.
  • Sampling bias in presence-only models - four remedies scored against each other, including the prediction step people forget and the spatial thinning that introduces a bias of its own.
  • Checking a presence-only model - clamping and extrapolation, the four output transforms, why AUC has a ceiling below one, and why a record split flatters the model.

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.
  • 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.

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.

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.

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.

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.

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.

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, and why a few patches dominate it.
  • 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.

Meta-analysis

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

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

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.

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.
  • 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.

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.

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.

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.
  • 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.
  • 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.