Type: Package
Title: Bayesian Priors for Matrix Population Models
Version: 1.0.4
Description: Provides functions to correct biased transition and fertility estimates in population projection matrices caused by small sample sizes. Small or short-term studies frequently produce structural zeros (biologically possible transitions never observed) and structural ones (transitions estimated at 100% survival, stasis, or mortality that are biologically implausible). Both distort matrix structure and bias estimates of population growth. Implements a multinomial-Dirichlet Bayesian prior for transition probabilities and a Gamma-Poisson prior for reproduction, allowing analysts to incorporate prior biological knowledge and regularise estimates from rare or unobserved events. Includes functions to compute marginal posterior credible intervals for all transition probabilities (transition_CrI()), visualise those intervals as point-range plots (plot_transition_CrI()), and display the full posterior beta density for each matrix entry (plot_transition_density()). Methods are described in Tremblay et al. (2021) <doi:10.1016/j.ecolmodel.2021.109526>.
URL: https://atiretoo.github.io/raretrans/, https://github.com/atiretoo/raretrans
BugReports: https://github.com/atiretoo/raretrans/issues
License: MIT + file LICENSE
Depends: R (≥ 4.1.0)
Imports: ggplot2, rlang, stats
Suggests: bslib, covr, dplyr, formatR, gridExtra, huxtable, knitr, MultinomialCI, popdemo, popbio, purrr, rmarkdown, RColorBrewer, shiny, testthat, tibble, tidyr
VignetteBuilder: knitr
Encoding: UTF-8
Language: en-US
LazyData: true
RoxygenNote: 7.3.3
NeedsCompilation: no
Packaged: 2026-04-17 14:23:21 UTC; rlt
Author: Raymond Tremblay ORCID iD [aut, cre, cph], Andrew Tyre ORCID iD [aut, cph], Maria-Eglee Perez ORCID iD [aut], Sasha Tenhumberg [ctb]
Maintainer: Raymond Tremblay <raymond.tremblay@upr.edu>
Repository: CRAN
Date/Publication: 2026-04-21 19:32:17 UTC

raretrans: Bayesian Priors for Matrix Population Models

Description

Provides functions to correct biased transition and fertility estimates in population projection matrices caused by small sample sizes. Small or short-term studies frequently produce structural zeros (biologically possible transitions never observed) and structural ones (transitions estimated at 100 Both distort matrix structure and bias estimates of population growth. Functions combine observed transition data with Bayesian prior beliefs to regularise estimates from rare or unobserved events.

Author(s)

Maintainer: Raymond Tremblay raymond.tremblay@upr.edu (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Transition and recruitment data for Lepanthes eltoroensis

Description

Individual-level census data from multiple populations of the epiphytic orchid Lepanthes eltoroensis Stimson, a critically rare species endemic to Puerto Rico. Individuals were permanently marked and surveyed at 6-month intervals over 12 census periods (6 calendar years). Each row represents one individual observed at one census period.

Usage

data(L_elto)

Format

A data frame with 5233 rows and 13 variables:

POPNUM

Integer. Population identifier number.

year

Integer. Census period number (each period represents a 6-month interval, not a calendar year; periods range from 1 to 12).

seedlings

Numeric. Population-level count of plantulas (seedlings, stage "p") observed in the population at this census period. The same value is repeated for all individuals in the same population-period combination.

adults

Numeric. Population-level count of adults (stage "a") observed in the population at this census period. The same value is repeated for all individuals in the same population-period combination.

fertility

Numeric. Mean per-individual fertility: average number of seedlings produced per adult in the population at this census period.

IND_NUM

Integer. Unique individual plant identifier number within its population.

stage

Character. Life history stage of the individual at the current census: "p" (plantula/seedling), "j" (juvenile), or "a" (adult). See Details for stage definitions.

next_stage

Character. Life history stage of the individual at the following 6-month census: "p", "j", "a", or "m" (muerto/dead). See Details for stage definitions.

first_year

Integer. 6-month census period number when the individual was first observed (1 = first survey).

last_year

Integer. 6-month census period number when the individual was last observed alive.

recruited

Logical. TRUE if this individual was newly recruited into the population (not present at the previous survey), typically via sexual reproduction. All individuals at the first census period (year == 1) are TRUE by definition as there is no prior survey for comparison.

died

Logical. Whether the individual was found dead at this census period.

lifespan

Integer. Total number of 6-month census periods during which the individual was observed alive (not in calendar years).

Details

Life history stages are coded as follows:

Source

Raymond L. Tremblay, University of Puerto Rico at Humacao, unpublished data.

References

Tremblay, R.L. and Hutchings, M.J. (2003). Population dynamics in orchid conservation: a review of analytical methods based on the rare species Lepanthes eltoroensis. In: Dixon, K.W. et al. (eds.) Orchid Conservation. Natural History Publications (Borneo), pp. 183–204.

Tremblay, R.L., Perez, M-E., Tyre, A.J. and Tenhumberg, B. (2021). Bayesian estimates for matrix population models of rare plants. Ecological Modelling, 440, 109526. doi:10.1016/j.ecolmodel.2021.109526


Combine prior and data for fertility matrix

Description

fill_fertility returns the expected value of the fertility matrix combining observed recruits for one time step and a Gamma prior for each column.

Usage

fill_fertility(
  TF,
  N,
  alpha = 1e-05,
  beta = 1e-05,
  priorweight = -1,
  returnType = "F"
)

Arguments

TF

A list of two matrices, T and F, as ouput by projection.matrix.

N

A vector of observed stage distribution.

alpha

A matrix of the prior parameter for each stage. Impossible stage combinations marked with NA_real_.

beta

A matrix of the prior parameter for each stage. Impossible stage combinations marked with NA_real_.

priorweight

total weight for each column of prior as a percentage of sample size or 1 if negative

returnType

A character vector describing the desired return value. Defaults to "F" the fertility matrix

Details

Assumes that only one stage reproduces ... needs generalizing.

Value

The return value depends on parameter returnType.

Examples

# Build a simple 3-stage TF list (transition + fertility matrices)
T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

# Only adults (stage 3) reproduce; mark non-reproducing entries with NA
alpha_mat <- matrix(c(NA, NA, 0.5,
                      NA, NA, NA,
                      NA, NA, NA), nrow = 3, ncol = 3)
beta_mat  <- matrix(c(NA, NA, 1.0,
                      NA, NA, NA,
                      NA, NA, NA), nrow = 3, ncol = 3)

# Default: return filled fertility matrix F
fill_fertility(TF, N, alpha = alpha_mat, beta = beta_mat)

# Return the full population matrix A = T + F
fill_fertility(TF, N, alpha = alpha_mat, beta = beta_mat, returnType = "A")

# Return the posterior alpha and beta parameters
fill_fertility(TF, N, alpha = alpha_mat, beta = beta_mat, returnType = "ab")

Combine prior and data for transition matrix

Description

fill_transition returns the expected value of the transition matrix combining observed transitions for one time step and a prior

Usage

fill_transitions(TF, N, P = NULL, priorweight = -1, returnType = "T")

Arguments

TF

A list of two matrices, T and F, as ouput by projection.matrix.

N

A vector of observed transitions.

P

A matrix of the priors for each column. Defaults to uniform.

priorweight

total weight for each column of prior as a percentage of sample size or 1 if negative

returnType

A character vector describing the desired return value. Defaults to "T" the transition matrix.

Value

The return value depends on parameter returnType.

Examples

# Build a simple 3-stage TF list (transition + fertility matrices)
T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

# Default: return filled transition matrix T
fill_transitions(TF, N)

# Return the full population matrix A = T + F
fill_transitions(TF, N, returnType = "A")

# Use a prior weight equal to the sample size
fill_transitions(TF, N, priorweight = 1)

Helper functions for generating different priors

Description

Extract the number of individuals in each stage from a dataframe of transitions.

Usage

get_state_vector(transitions, stage = NULL, sort = NULL)

Arguments

transitions

a dataframe of observations of individuals in different stages

stage

the name of the variable with the stage information

sort

a vector of stage names in the desired order. Default is the order of levels in stage.

Value

a vector of the counts of observations in each level of stage.

Examples

data("L_elto")

# Extract one population at one census period
onepop <- L_elto[L_elto$POPNUM == 250 & L_elto$year == 5, ]
onepop$stage <- factor(onepop$stage, levels = c("p", "j", "a"))

# Count individuals per stage in the order p, j, a
get_state_vector(onepop, stage = "stage", sort = c("p", "j", "a"))

Plot beta credible intervals for transition matrix entries

Description

Creates a ggplot2 visualisation of the posterior mean transition probabilities and their credible intervals for each stage, including the probability of dying. Each panel shows the fate distribution from one source stage.

Usage

plot_transition_CrI(
  cri,
  include_dead = TRUE,
  title = "Posterior transition probabilities with credible intervals"
)

Arguments

cri

A data frame as returned by transition_CrI.

include_dead

Logical. Whether to include the dead fate in the plot. Defaults to TRUE.

title

Character. Plot title. Defaults to "Posterior transition probabilities with credible intervals".

Value

A ggplot object.

See Also

transition_CrI for computing the credible intervals.

Examples

T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

cri <- transition_CrI(TF, N, stage_names = c("plantula", "juvenile", "adult"))

# Include dead fate (default)
plot_transition_CrI(cri)

# Exclude dead fate
plot_transition_CrI(cri, include_dead = FALSE)

Plot posterior beta density curves for all transition matrix entries

Description

Creates a ggplot2 visualisation arranged as an n \times n matrix of density plots, mirroring the structure of the population projection matrix. Each panel shows the full marginal posterior beta distribution for one transition probability, with the credible interval region shaded. Columns correspond to source stages (from) and rows to destination stages (to), including the dead fate as the bottom row.

Usage

plot_transition_density(
  TF,
  N,
  P = NULL,
  priorweight = -1,
  ci = 0.95,
  stage_names = NULL,
  include_dead = TRUE,
  title = "Posterior transition probability densities"
)

Arguments

TF

A list of two matrices, T and F, as output by projection.matrix.

N

A vector of observed stage distribution at the start of the transition period.

P

A matrix of priors for each column. Defaults to uniform.

priorweight

Total weight for each column of prior as a percentage of sample size, or 1 if negative. Defaults to -1 (uninformative).

ci

Credible interval width as a probability between 0 and 1. The shaded region in each panel covers this interval. Defaults to 0.95.

stage_names

Optional character vector of stage names in the same order as the columns of the transition matrix. If NULL, names are taken from colnames(TF$T), or generic labels are used.

include_dead

Logical. Whether to include the dead fate as the bottom row of the matrix plot. Defaults to TRUE.

title

Character. Plot title.

Value

A ggplot object arranged as an n \times n grid (or (n+1) \times n when include_dead = TRUE), with source stages as columns and destination stages as rows.

See Also

transition_CrI, plot_transition_CrI.

Examples

T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

# Include dead fate as bottom row (default)
plot_transition_density(TF, N,
                        stage_names = c("plantula", "juvenile", "adult"))

# Transitions only, no dead row
plot_transition_density(TF, N,
                        stage_names = c("plantula", "juvenile", "adult"),
                        include_dead = FALSE)

Dirichlet distributed random numbers

Description

Generate n random vectors distributed according to a Dirichlet distribution. Each row of the returned matrix is a random vector that sums to 1.

Usage

rdirichlet(n, alpha)

Arguments

n

The number of random vectors to generate

alpha

A vector of parameters

Value

The function returns a matrix with n rows and length(alpha) columns

Source

copied from package MCMCpack to avoid a dependency. That code was taken from Greg's Miscellaneous Functions (gregmisc). His code was based on code posted by Ben Bolker to R-News on 15 Dec 2000.

Examples

# Generate 5 random probability vectors from a Dirichlet(1, 2, 3) distribution
set.seed(42)
rdirichlet(5, c(1, 2, 3))


Run the interactive Shiny application for Bayesian transition priors

Description

Run the interactive Shiny application for Bayesian transition priors

Usage

run_app()

Value

No return value, called for side effects (launches a Shiny app).

Examples

if(interactive()){
raretrans::run_app()
}

Simulate population projection matrices

Description

sim_transition generates a list of simulated population projection matrices from the provided parameters and prior distributions.

Usage

sim_transitions(
  TF,
  N,
  P = NULL,
  alpha = 1e-05,
  beta = 1e-05,
  priorweight = -1,
  samples = 1
)

Arguments

TF

A list of two matrices, T and F, as ouput by projection.matrix.

N

A vector of observed stages at start of transition.

P

A matrix of the priors for each column. Defaults to uniform.

alpha

A matrix of the prior parameter for each stage. Impossible stage combinations marked with NA_real_.

beta

A matrix of the prior parameter for each stage. Impossible stage combinations marked with NA_real_.

priorweight

total weight for each column of prior as a percentage of sample size or 1 if negative

samples

The number of matrices to return.

Value

Always returns a list.

Examples

# Build a simple 3-stage TF list
T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

# Simulate 10 population projection matrices using default uninformative priors
set.seed(42)
mats <- sim_transitions(TF, N, samples = 10)
length(mats)   # 10 matrices
mats[[1]]      # first simulated matrix

Calculate beta credible intervals for all transition matrix entries

Description

Computes the marginal posterior beta credible intervals for every entry in the transition matrix, including the probability of dying. The marginal posterior distribution of each transition probability follows a beta distribution derived from the Dirichlet-multinomial model, using the augmented fate matrix (TN) returned by fill_transitions.

Usage

transition_CrI(
  TF,
  N,
  P = NULL,
  priorweight = -1,
  ci = 0.95,
  stage_names = NULL
)

Arguments

TF

A list of two matrices, T and F, as output by projection.matrix.

N

A vector of observed stage distribution at the start of the transition period.

P

A matrix of priors for each column. Defaults to uniform.

priorweight

Total weight for each column of prior as a percentage of sample size, or 1 if negative. Defaults to -1 (uninformative).

ci

Credible interval width as a probability between 0 and 1. Defaults to 0.95 (95% credible interval).

stage_names

Optional character vector of stage names in the same order as the columns of the transition matrix. If NULL, names are taken from colnames(TF$T), or generic labels "Stage 1", "Stage 2", etc. are used.

Value

A data frame with one row per fate per stage (including the dead fate) and the following columns:

from_stage

Character. The source stage (column of the matrix).

to_stage

Character. The destination stage, including "dead".

mean

Numeric. Posterior mean transition probability.

lower

Numeric. Lower bound of the credible interval.

upper

Numeric. Upper bound of the credible interval.

See Also

plot_transition_CrI for visualising the output.

Examples

T_mat <- matrix(c(0.5, 0.3, 0.0,
                  0.2, 0.4, 0.1,
                  0.0, 0.1, 0.7), nrow = 3, ncol = 3)
F_mat <- matrix(c(0.0, 0.0, 1.5,
                  0.0, 0.0, 0.0,
                  0.0, 0.0, 0.0), nrow = 3, ncol = 3)
TF <- list(T = T_mat, F = F_mat)
N  <- c(10, 5, 8)

# Default 95% credible intervals
cri <- transition_CrI(TF, N, stage_names = c("plantula", "juvenile", "adult"))
cri

# 90% credible intervals
transition_CrI(TF, N, stage_names = c("plantula", "juvenile", "adult"), ci = 0.90)