View source: R/simulate_from_gam.R
summarise_posterior | R Documentation |
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.
summarise_posterior(pmat, probs = c(0.025, 0.975), summary_format = "list")
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 |
The function returns a list or a matrix, depending on the input to summary_format
.
Edward Lavender
#### 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) utils::head(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" prettyGraphics::add_error_envelope(x = nd$x, ci = summary3, add_ci = list(col = "dimgrey", border = FALSE ) )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.