# summarise_posterior: Summarise a posterior distribution matrix In edwardlavender/Tools4ETS: Tools for Ecological Time Series

 summarise_posterior R Documentation

## Summarise a posterior distribution matrix

### Description

This function calculates summarises of a posterior distribution matrix, in which each row is an observation and each column is a sample from the posterior distribution for that observation, that can be used to create confidence intervals (or similar) around a fitted line (or similar) based on the posterior simulation.

### Usage

summarise_posterior(pmat, probs = c(0.025, 0.975), summary_format = "list")

### Arguments

 pmat A matrix which defines the full posterior distribution. Each row is an observation; each column is a sample from the posterior distribution for that observation. probs A numeric vector of probabilities which define the desired lower and upper confidence intervals (or similar) respectively. summary_format A character input which defines the output format desired. If "list", a list is returned with three elements: mean, lowerCI, upperCI. Otherwise, a matrix is returned with a column for the mean, lowerCI and upperCI values for each observation.

### Value

The function returns a list or a matrix, depending on the input to summary_format.

Edward Lavender

### Examples

#### Simulate some data and fit a GAM
set.seed(1)
nobs <- 100
x <- stats::runif(nobs, 0, 1000)
mu <- 0.001 * x^2
y <- stats::rnorm(nobs, mu, 100)
plot(x, y)
d <- data.frame(x = x, y = y)
m1 <- mgcv::gam(y ~ s(x), data = d)

#### Simulate the posterior distribution matrix with simulate_posterior_mu()
nd <- data.frame(x = seq(min(d\$x), max(d\$x), length.out = 100))
sim1 <- simulate_posterior_mu(
model = m1,
newdata = nd,
n = 1000,
return = "full")
# Now we have a matrix in which each row is an observation,
# ... and each column is a simulated value for the mean
utils::str(sim1)

#### Example (1) Summarise the posterior distribution matrix and return a list:
summary1 <-
summarise_posterior(pmat = sim1,
probs = c(0.025, 0.975),
summary_format = "list")
utils::str(summary1)
# This can be plotted with prettyGraphics::add_error_envelope()
# ... see (below).

#### Example (2) Summarise the posterior in a matrix:
# any value for summary_format other than "list" will return a matrix
summary2 <-
summarise_posterior(pmat = sim1,
probs = c(0.025, 0.0975),
summary_format = "matrix")
utils::str(summary2)

#### Example (3) Adjust the quantiles of the distribution returned:
summary3 <-
summarise_posterior(pmat = sim1,
probs = c(0.055, 0.945),
summary_format = "list")
utils::str(summary3)

#### Summarised posterior distributions can be plotted with add_error_envelope()
plot(d\$x, d\$y)
# 95 % CIs with mean
names(summary1)[1] <- "fit"
prettyGraphics::add_error_envelope(x = nd\$x, ci = summary1)
# 89% CIs:
names(summary3)[1] <- "fit"