### Install bayestestR Development Version Source: https://github.com/easystats/bayestestr/blob/main/README.md Install the latest development version of bayestestR from the R-universe repository. ```r install.packages("bayestestR", repos = "https://easystats.r-universe.dev") ``` -------------------------------- ### Installation Failure Message Source: https://github.com/easystats/bayestestr/blob/main/revdep/failures.md This message indicates that the package installation failed. Refer to the specified file for detailed error information. ```text Installation failed. See 'D:/mail/Documents/Coding/R/easystats/bayestestR/revdep/checks/snSMART/new/snSMART.Rcheck/00install.out' for details. ``` -------------------------------- ### R Package Installation Error (Devel) Source: https://github.com/easystats/bayestestr/blob/main/revdep/failures.md This output shows the process of installing the 'snSMART' R package from source. The installation halts due to an error during the loading of the 'rjags' package, which requires JAGS version 4 or higher to be installed. ```text * installing *source* package 'snSMART' ... ** package 'snSMART' successfully unpacked and MD5 sums checked ** using staged installation ** R ** data *** moving datasets to lazyload DB ** byte-compile and prepare package for lazy loading Error: .onLoad failed in loadNamespace() for 'rjags', details: call: fun(libname, pkgname) error: Failed to locate any version of JAGS version 4 The rjags package is just an interface to the JAGS library Make sure you have installed JAGS-4.x.y.exe (for any x >=0, y>=0) from http://www.sourceforge.net/projects/mcmc-jags/files Execution halted ERROR: lazy loading failed for package 'snSMART' * removing 'D:/mail/Documents/Coding/R/easystats/bayestestR/revdep/checks/snSMART/new/snSMART.Rcheck/snSMART' ``` -------------------------------- ### Print All Posterior Summaries Source: https://github.com/easystats/bayestestr/blob/main/tests/testthat/_snaps/windows/print.md This example demonstrates how to print all components of the posterior summary, including fixed effects and random effects, by setting effects and component to 'all'. It shows detailed statistics for each parameter type. ```r describe_posterior(m, effects = "all", component = "all", verbose = FALSE) ``` -------------------------------- ### Install bayestestR Package Source: https://context7.com/easystats/bayestestr/llms.txt Installs the stable release from CRAN or the development version from R-universe. Loads the library for use. ```r install.packages("bayestestR") ``` ```r install.packages("bayestestR", repos = "https://easystats.r-universe.dev") ``` ```r library(bayestestR) ``` -------------------------------- ### Install bayestestR from CRAN Source: https://github.com/easystats/bayestestr/blob/main/README.md Use this command to install the stable release version of the bayestestR package from CRAN. ```r install.packages("bayestestR") ``` -------------------------------- ### R Package Installation Error (CRAN) Source: https://github.com/easystats/bayestestr/blob/main/revdep/failures.md This output details the installation of the 'snSMART' R package from CRAN. Similar to the development version, the installation fails because the 'rjags' package cannot find the necessary JAGS library (version 4+). ```text * installing *source* package 'snSMART' ... ** package 'snSMART' successfully unpacked and MD5 sums checked ** using staged installation ** R ** data *** moving datasets to lazyload DB ** byte-compile and prepare package for lazy loading Error: .onLoad failed in loadNamespace() for 'rjags', details: call: fun(libname, pkgname) error: Failed to locate any version of JAGS version 4 The rjags package is just an interface to the JAGS library Make sure you have installed JAGS-4.x.y.exe (for any x >=0, y>=0) from http://www.sourceforge.net/projects/mcmc-jags/files Execution halted ERROR: lazy loading failed for package 'snSMART' * removing 'D:/mail/Documents/Coding/R/easystats/bayestestR/revdep/checks/snSMART/old/snSMART.Rcheck/snSMART' ``` -------------------------------- ### distribution() / distribution_normal() etc. Source: https://context7.com/easystats/bayestestr/llms.txt Generates a sample of size n that follows the specified theoretical distribution with near-perfect accuracy by computing quantiles of ppoints(n). Useful for testing and visualisation where reproducible, idealized samples are needed. ```APIDOC ## `distribution()` / `distribution_normal()` etc. — Near-Perfect Distributions Generates a sample of size `n` that follows the specified theoretical distribution with near-perfect accuracy by computing quantiles of `ppoints(n)`, rather than drawing random samples. Useful for testing and visualisation where reproducible, idealized samples are needed. ```r library(bayestestr) # Uniform quantile-based perfect distributions (no randomness) x_normal <- distribution_normal(n = 1000, mean = 0, sd = 1) x_gamma <- distribution_gamma(n = 1000, shape = 2, rate = 1) x_beta <- distribution_beta(n = 1000, shape1 = 2, shape2 = 5) x_chisq <- distribution_chisquared(n = 1000, df = 3) x_student <- distribution_student(n = 1000, df = 5) # Generic wrapper x <- distribution(type = "normal", n = 500, mean = 3, sd = 2) # Compare to random sampling set.seed(1) random <- rnorm(20) perfect <- distribution_normal(20) var(random) # varies each run ≈ 1 var(perfect) # always exactly near 1 — deterministic # Used in Bayes factor computation to supply prior samples prior <- distribution_normal(10000, mean = 0, sd = 1) posterior <- distribution_normal(10000, mean = 0.8, sd = 0.4) bayesfactor_parameters(posterior, prior, null = 0) ``` ``` -------------------------------- ### Estimate density using various methods Source: https://context7.com/easystats/bayestestr/llms.txt A unified wrapper for density estimation methods like kernel, logspline, KernSmooth, and mixture. Returns x/y pairs for plotting and supports grouped estimation via the `by` argument. Useful for visualizing data distributions. ```r library(bayestestR) set.seed(1) x <- rnorm(500, mean = 1) # Default: kernel density with bandwidth "SJ" d <- estimate_density(x) head(d) # x y # 1 -1.427926 0.00186267 # 2 -1.417310 0.00192476 # ... # Different methods d_logspline <- estimate_density(x, method = "logspline") d_kernsmooth <- estimate_density(x, method = "KernSmooth") # Plot comparison plot(d$x, d$y, type = "l", lwd = 2, main = "Density estimation methods") lines(d_logspline$x, d_logspline$y, col = "red", lwd = 2) lines(d_kernsmooth$x, d_kernsmooth$y, col = "blue", lwd = 2) legend("topright", c("kernel", "logspline", "KernSmooth"), col = c("black", "red", "blue"), lwd = 2) # Grouped estimation head(estimate_density(iris, by = "Species")) ``` -------------------------------- ### Generate idealized distribution samples Source: https://context7.com/easystats/bayestestr/llms.txt Generates reproducible, idealized samples from theoretical distributions by computing quantiles of `ppoints(n)`. Useful for testing and visualization where deterministic samples are needed. Can be used to supply prior samples for Bayes factor computations. ```r library(bayestestR) # Uniform quantile-based perfect distributions (no randomness) x_normal <- distribution_normal(n = 1000, mean = 0, sd = 1) x_gamma <- distribution_gamma(n = 1000, shape = 2, rate = 1) x_beta <- distribution_beta(n = 1000, shape1 = 2, shape2 = 5) x_chisq <- distribution_chisquared(n = 1000, df = 3) x_student <- distribution_student(n = 1000, df = 5) # Generic wrapper x <- distribution(type = "normal", n = 500, mean = 3, sd = 2) # Compare to random sampling set.seed(1) random <- rnorm(20) perfect <- distribution_normal(20) var(random) # varies each run ≈ 1 var(perfect) # always exactly near 1 — deterministic # Used in Bayes factor computation to supply prior samples prior <- distribution_normal(10000, mean = 0, sd = 1) posterior <- distribution_normal(10000, mean = 0.8, sd = 0.4) bayesfactor_parameters(posterior, prior, null = 0) ``` -------------------------------- ### Generate Near-Perfect Distributions Source: https://github.com/easystats/bayestestr/blob/main/README.md The distribution() function generates a sample of a specified size with distributions that are close to perfect. Use this for creating test data or simulating specific distribution shapes. ```r distribution(n = 10) ## [1] -1.55 -1.00 -0.66 -0.38 -0.12 0.12 0.38 0.66 1.00 1.55 ``` -------------------------------- ### diagnostic_posterior() Source: https://context7.com/easystats/bayestestr/llms.txt Extracts sampling diagnostics from MCMC-based models: Effective Sample Size (ESS, both tail and bulk), Rhat (convergence), and Monte Carlo Standard Error (MCSE). ```APIDOC ## `diagnostic_posterior()` — MCMC Sampling Diagnostics Extracts **sampling diagnostics** from MCMC-based models: Effective Sample Size (ESS, both tail and bulk), Rhat (convergence), and Monte Carlo Standard Error (MCSE). ESS should exceed 1000; Rhat should be ≤ 1.01; MCSE quantifies estimation noise. ```r library(bayestestr) # Diagnostics from raw MCMC chain lists set.seed(101) chains <- replicate( 4, as.data.frame(replicate(3, rnorm(1000))), simplify = FALSE ) names(chains) <- NULL for (i in seq_along(chains)) colnames(chains[[i]]) <- c("alpha", "beta", "sigma") diagnostic_posterior(chains, diagnostic = "all") # Parameter | ESS | ESS_bulk | Rhat | MCSE # ------------------------------------------- # alpha | 989 | 1002 | 1.000 | 0.032 # beta | 997 | 998 | 0.999 | 0.032 # sigma | 985 | 994 | 1.001 | 0.031 # From a fitted model # model <- rstanarm::stan_glm(mpg ~ wt + gear, data = mtcars, # chains = 4, iter = 2000, refresh = 0) # diagnostic_posterior(model, diagnostic = c("ESS", "Rhat")) # Parameter | ESS | Rhat # -------------------------- # (Intercept) | 3822 | 1 # wt | 3518 | 1 # gear | 4012 | 1 ``` ``` -------------------------------- ### eti() — Equal-Tailed Interval Source: https://context7.com/easystats/bayestestr/llms.txt Computes the Equal-Tailed Interval (ETI) using quantiles. The probability of being below the lower bound equals the probability of being above the upper bound. It always includes the median and is preferred when the posterior will be back-transformed. ```APIDOC ## `eti()` — Equal-Tailed Interval Computes the **Equal-Tailed Interval (ETI)** using quantiles. The probability of being below the lower bound equals the probability of being above the upper bound (i.e., 2.5% on each side for a 95% ETI). Always includes the median; preferred when the posterior will be back-transformed. ### Parameters - **posterior** (numeric vector or object) - The posterior distribution samples. - **ci** (numeric, optional) - The confidence interval level(s) (e.g., 0.95 for 95%). Defaults to 0.95. ### Request Example ```r library(bayestestR) posterior <- rnorm(5000, mean = 2, sd = 1) eti(posterior, ci = 0.95) ``` ### Response Example ``` # 95% ETI: [0.04, 3.96] ``` ### Additional Examples ```r # Comparison with HDI on a skewed distribution skewed <- distribution_gamma(5000, shape = 2, rate = 1) eti(skewed, ci = 0.95) # 95% ETI: [0.10, 5.62] hdi(skewed, ci = 0.95) # 95% HDI: [0.06, 5.24] # narrower — HDI is always the shortest interval # Multiple CI levels eti(posterior, ci = c(0.80, 0.89, 0.95)) ``` ### Response Example (Multiple CIs) ``` # CI | CI_low | CI_high # ---------------------- # 0.80 | 0.72 | 3.28 # 0.89 | 0.31 | 3.69 # 0.95 | 0.04 | 3.96 ``` ``` -------------------------------- ### Describe Posterior Distribution of brmsfit Model Source: https://github.com/easystats/bayestestr/blob/main/README.md Use `describe_posterior()` to summarize the posterior distribution of a brmsfit model. Specify effects, components, and desired tests for detailed output. ```r zinb <- read.csv("http://stats.idre.ucla.edu/stat/data/fish.csv") set.seed(123) model <- brm( bf( count ~ child + camper + (1 | persons), zi ~ child + camper + (1 | persons) ), data = zinb, family = zero_inflated_poisson(), chains = 1, iter = 500 ) describe_posterior( model, effects = "all", component = "all", test = c("p_direction", "p_significance"), centrality = "all" ) ``` -------------------------------- ### Describe Posterior Distribution with describe_posterior() Source: https://context7.com/easystats/bayestestr/llms.txt Computes key posterior indices like median, MAD, HDI, probability of direction, and ROPE percentage. Can accept numeric vectors, data frames, or model objects. Use test = NULL or centrality = NULL to suppress components. ```r set.seed(42) posterior <- rnorm(10000, mean = 0.5, sd = 0.3) describe_posterior( posterior, centrality = "median", dispersion = TRUE, ci = 0.95, ci_method = "HDI", test = c("p_direction", "rope", "p_significance"), rope_range = c(-0.1, 0.1), verbose = FALSE ) ``` ```r df <- data.frame( alpha = rnorm(1000, 0.8, 0.2), beta = rnorm(1000, -0.3, 0.4) ) describe_posterior(df, centrality = "all", dispersion = TRUE, test = "all", verbose = FALSE) ``` ```r # model <- brms::brm(mpg ~ wt + cyl, data = mtcars, # chains = 2, iter = 1000, refresh = 0) # describe_posterior( # model, # effects = "fixed", # component = "conditional", # test = c("p_direction", "rope"), # ci_method = "ETI" # ) ``` -------------------------------- ### Load bayestestR Package Source: https://github.com/easystats/bayestestr/blob/main/README.md Load the bayestestR package into your R session to use its functions. For access to the entire easystats ecosystem, use library(easystats). ```r library("bayestestR") ``` -------------------------------- ### Print Default Posterior Summary Source: https://github.com/easystats/bayestestr/blob/main/tests/testthat/_snaps/windows/print.md This snippet shows the default output of describe_posterior when verbose is set to FALSE. It includes median, 95% CI, probability of direction (pd), region of practical equivalence (ROPE), and Rhat/ESS for each parameter. ```r describe_posterior(m, verbose = FALSE) ``` -------------------------------- ### Calculate MAP Estimate of Posterior Distribution Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Use `map_estimate()` for a direct calculation of the Maximum A Posteriori estimate. Requires a posterior distribution as input. ```r set.seed(1) posterior <- rchisq(100, 3) map_estimate(posterior) ``` -------------------------------- ### estimate_density() Source: https://context7.com/easystats/bayestestr/llms.txt A unified wrapper over multiple density estimation methods. Returns a data frame of x/y pairs suitable for plotting. Supports grouped estimation via the `by` argument. ```APIDOC ## `estimate_density()` — Density Estimation A unified wrapper over multiple density estimation methods (`"kernel"`, `"logspline"`, `"KernSmooth"`, `"mixture"`). Returns a data frame of x/y pairs suitable for plotting. Used internally by `map_estimate()` and `p_direction(method = "kernel")`. Supports grouped estimation via the `by` argument. ```r library(bayestestr) set.seed(1) x <- rnorm(500, mean = 1) # Default: kernel density with bandwidth "SJ" d <- estimate_density(x) head(d) # x y # 1 -1.427926 0.00186267 # 2 -1.417310 0.00192476 # ... # Different methods d_logspline <- estimate_density(x, method = "logspline") d_kernsmooth <- estimate_density(x, method = "KernSmooth") # Plot comparison plot(d$x, d$y, type = "l", lwd = 2, main = "Density estimation methods") lines(d_logspline$x, d_logspline$y, col = "red", lwd = 2) lines(d_kernsmooth$x, d_kernsmooth$y, col = "blue", lwd = 2) legend("topright", c("kernel", "logspline", "KernSmooth"), col = c("black", "red", "blue"), lwd = 2) # Grouped estimation head(estimate_density(iris, by = "Species")) ``` ``` -------------------------------- ### Compute Density at a Specific Point Source: https://github.com/easystats/bayestestr/blob/main/README.md Use density_at() to calculate the density of a given point within a distribution. This is helpful for understanding the probability density at specific values. ```r density_at(rnorm(1000, 1, 1), 1) ## [1] 0.39 ``` -------------------------------- ### Visualize and Apply to Models Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Visualize bayestestR results using the plot() function from the see package. Functions can also be directly applied to statistical models fitted with packages like rstanarm or brms to describe model parameters. ```r # Load the rstanarm and the see package library(rstanarm) library(see) # Fit a Bayesian linear regression model <- stan_glm(Petal.Width ~ Petal.Length * Sepal.Width, data = iris) # Store results result_pd <- p_direction(model) # Print and plot results print(result_pd) # Probability of Direction (pd) Parameter pd (Intercept) 72.47% Petal.Length 99.88% Sepal.Width 70.97% Petal.Length:Sepal.Width 96.70% plot(result_pd) ``` -------------------------------- ### Calculate Equal-Tailed Interval (ETI) Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Compute the Equal-Tailed Interval (ETI) of a posterior distribution using `eti()`. By default, it returns the 89% interval. ```r eti(posterior) ``` -------------------------------- ### Print Equivalence Test Output (rstanarm) Source: https://github.com/easystats/bayestestr/blob/main/tests/testthat/_snaps/equivalence_test.md Displays the results of an equivalence test performed using the rstanarm package. Shows ROPE, H0 status, and HDI for parameters. ```r print(out) ``` -------------------------------- ### rope() — Region of Practical Equivalence Source: https://context7.com/easystats/bayestestr/llms.txt Computes the proportion of the posterior's credible interval that falls within a Region of Practical Equivalence (ROPE). A high percentage inside the ROPE supports the null hypothesis; a low percentage rejects it. ```APIDOC ## `rope()` — Region of Practical Equivalence Computes the proportion of the posterior's credible interval that falls within a **Region of Practical Equivalence (ROPE)** — a range of values considered practically equivalent to zero. A high percentage inside the ROPE supports the null hypothesis; a low percentage rejects it. Use `complement = TRUE` to also retrieve the proportions above/below the ROPE. ### Parameters - **posterior** (numeric vector, data frame, or model object) - The posterior distribution samples or a model object. - **range** (numeric vector or list) - The ROPE range(s). For a single posterior, a numeric vector `c(lower, upper)`. For models, a list of named ranges for each parameter. - **ci** (numeric, optional) - The confidence interval level(s). Defaults to 0.95. - **complement** (logical, optional) - If TRUE, also returns proportions outside the ROPE. Defaults to FALSE. ### Request Example (Nearly-Null Effect) ```r library(bayestestR) # Nearly-null effect — most of posterior inside ROPE posterior_null <- rnorm(10000, mean = 0.0, sd = 0.05) rope(posterior_null, range = c(-0.1, 0.1)) ``` ### Response Example (Nearly-Null Effect) ``` # # Proportion of samples inside the ROPE [-0.10, 0.10]: # Inside ROPE: 95.24% ``` ### Request Example (Clear Positive Effect) ```r # Clear positive effect — very little inside ROPE posterior_effect <- rnorm(10000, mean = 0.5, sd = 0.2) rope(posterior_effect, range = c(-0.1, 0.1), ci = 0.95) ``` ### Response Example (Clear Positive Effect) ``` # Inside ROPE: 1.03% ``` ### Request Example (Multiple CIs + Complementary Probabilities) ```r rope( posterior_effect, range = c(-0.1, 0.1), ci = c(0.89, 0.95), complement = TRUE ) ``` ### Response Example (Multiple CIs + Complementary Probabilities) ``` # CI | ROPE_low | ROPE_high | ROPE_Percentage | Superiority_Percentage # 0.89 | -0.10 | 0.10 | 0.91 | 99.09 # 0.95 | -0.10 | 0.10 | 1.03 | 98.97 ``` ### Request Example (Model with Named ROPE Ranges) ```r # Model with named per-parameter ROPE ranges # model <- rstanarm::stan_glm(mpg ~ wt + gear, data = mtcars, refresh = 0) # rope(model, range = list(wt = c(-0.5, 0.5), gear = c(-1, 1))) ``` ``` -------------------------------- ### Calculate Highest Density Interval (HDI) with hdi() Source: https://context7.com/easystats/bayestestr/llms.txt Computes the shortest interval containing a given probability mass, suitable for skewed posteriors. Supports multiple CI levels and various input types including numeric vectors, data frames, and model objects. ```r posterior <- distribution_chisquared(10000, df = 4) hdi(posterior, ci = 0.89) ``` ```r hdi(posterior, ci = c(0.50, 0.89, 0.95)) ``` ```r df <- data.frame( param1 = rnorm(2000, 1, 0.5), param2 = rgamma(2000, 2, 1) ) hdi(df, ci = 0.95) ``` ```r # model <- rstanarm::stan_glm(mpg ~ wt + gear, data = mtcars, # chains = 2, iter = 200, refresh = 0) # hdi(model, ci = c(0.80, 0.95), effects = "fixed") ``` -------------------------------- ### bayesfactor_parameters Source: https://context7.com/easystats/bayestestr/llms.txt Computes a Bayes factor (BF) for a single parameter against a point-null or an interval-null using the Savage-Dickey density ratio. Requires informative priors. ```APIDOC ## bayesfactor_parameters() / bf_parameters() ### Description Computes a **Bayes factor (BF)** for a single parameter against a point-null (Savage-Dickey density ratio) or an interval-null. A BF > 1 indicates evidence against the null; BF < 1 indicates evidence for the null. Requires informative priors; flat priors will produce meaningless results. ### Method `bayesfactor_parameters(posterior, prior, null, direction)` ### Parameters - **posterior** (numeric vector or model object): The posterior distribution or model. - **prior** (numeric vector or model object): The prior distribution or model. - **null** (numeric value or vector): The null hypothesis value or interval. - **direction** (string, optional): Specifies the direction of the test ('two-sided', 'left', 'right'). Defaults to 'two-sided'. ### Request Example ```r library(bayestestR) # Savage-Dickey ratio: point null = 0, two-sided set.seed(123) prior <- distribution_normal(10000, mean = 0, sd = 1) posterior <- distribution_normal(10000, mean = 1.0, sd = 0.5) bf <- bayesfactor_parameters(posterior, prior, null = 0, direction = "two-sided") bf ``` ### Response Returns a Bayes Factor object with methods for printing and conversion to numeric values. #### Success Response (BF object) - **BF** (numeric): The calculated Bayes Factor. #### Response Example ``` # Bayes Factor (Savage-Dickey density ratio) # BF # ---- # 7.36 # * Evidence Against The Null: 0 ``` ### Additional Examples ```r # Interval-null (ROPE-based BF) bayesfactor_parameters(posterior, prior, null = c(-0.1, 0.1)) # One-sided test: evidence that parameter > 0 bayesfactor_parameters(posterior, prior, null = 0, direction = "right") # From a rstanarm / brms model (prior extracted automatically via unupdate()) # model <- rstanarm::stan_glm(mpg ~ wt + cyl, data = mtcars, # prior = normal(0, 1), refresh = 0) # bayesfactor_parameters(model) ``` ``` -------------------------------- ### Perform Equivalence Test Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Conducts a test for practical equivalence using the HDI+ROPE decision rule. This helps determine if parameter values should be accepted or rejected against a null hypothesis defined by a ROPE. Requires a fitted model object. ```r library(rstanarm) model <- stan_glm(mpg ~ wt + gear, data = mtcars) equivalence_test(model) ``` -------------------------------- ### Describe Posterior Distribution Source: https://github.com/easystats/bayestestr/blob/main/README.md Use `describe_posterior` to compute various summary indices of a posterior distribution at once. Specify desired centrality measures and tests. Set `verbose = FALSE` to suppress summary output. ```r describe_posterior( rnorm(10000), centrality = "median", test = c("p_direction", "p_significance"), verbose = FALSE ) ## Summary of Posterior Distribution ## ## Parameter | Median | 95% CI | pd | ps ## ----------------------------------------------------- ``` -------------------------------- ### Compute Equal-Tailed Interval (ETI) using Quantiles Source: https://context7.com/easystats/bayestestr/llms.txt Calculates the Equal-Tailed Interval (ETI) for a given posterior distribution. Useful for back-transformed posteriors. Specify the desired confidence interval (ci) level. ```r library(bayestestR) posterior <- rnorm(5000, mean = 2, sd = 1) eti(posterior, ci = 0.95) # 95% ETI: [0.04, 3.96] # Comparison with HDI on a skewed distribution skewed <- distribution_gamma(5000, shape = 2, rate = 1) eti(skewed, ci = 0.95) # 95% ETI: [0.10, 5.62] hdi(skewed, ci = 0.95) # 95% HDI: [0.06, 5.24] # narrower — HDI is always the shortest interval # Multiple CI levels eti(posterior, ci = c(0.80, 0.89, 0.95)) ``` -------------------------------- ### describe_posterior() — Full posterior summary Source: https://context7.com/easystats/bayestestr/llms.txt The master function that computes all key indices (point estimates, credible intervals, ROPE, probability of direction, Bayes factors) in one call. Accepts numeric vectors, data frames, stanreg, brmsfit, BFBayesFactor, emmGrid, draws/rvar, and many other classes. Use test = NULL or centrality = NULL to suppress individual components. ```APIDOC ## describe_posterior() ### Description Computes key indices like point estimates, credible intervals, ROPE, probability of direction, and Bayes factors from posterior distributions. ### Parameters - **posterior**: Numeric vector, data frame, or Bayesian model object. - **centrality**: Character or NULL. Specifies which centrality measures to compute (e.g., "median", "mean", "all"). - **dispersion**: Logical. Whether to compute dispersion measures. - **ci**: Numeric. The confidence interval level (e.g., 0.95 for 95% CI). - **ci_method**: Character. Method for computing CI (e.g., "HDI", "ETI"). - **test**: Character or NULL. Specifies which hypothesis tests to perform (e.g., "p_direction", "rope", "all"). - **rope_range**: Numeric vector. The range for the Region Of Practical Equivalence (ROPE). - **verbose**: Logical. Whether to print detailed output. - **effects**: Character. For model objects, specifies which effects to consider (e.g., "fixed"). - **component**: Character. For model objects, specifies the component (e.g., "conditional"). ### Request Example ```r library(bayestestR) set.seed(42) posterior <- rnorm(10000, mean = 0.5, sd = 0.3) describe_posterior( posterior, centrality = "median", dispersion = TRUE, ci = 0.95, ci_method = "HDI", test = c("p_direction", "rope", "p_significance"), rope_range = c(-0.1, 0.1), verbose = FALSE ) ``` ### Response Example ``` # Summary of Posterior Distribution # # Parameter | Median | MAD | 95% HDI | pd | ps | % in ROPE # ------------------------------------------------------------------------- # Posterior | 0.50 | 0.302 | [-0.09, 1.09] | 95.19% | 0.89 | 6.94 ``` ``` -------------------------------- ### rope_range() Source: https://context7.com/easystats/bayestestr/llms.txt Automatically computes suitable ROPE bounds from a model object based on the response type. For linear models uses ±0.1 * SD(y); for logistic models uses ±0.18; for t-tests uses ±0.1 * SD(response). Intended to be passed directly to rope() or describe_posterior(). ```APIDOC ## `rope_range()` — Automatic ROPE Boundary Detection Automatically computes suitable ROPE bounds from a model object based on the response type. For linear models uses `±0.1 * SD(y)`; for logistic models uses `±0.18`; for t-tests uses `±0.1 * SD(response)`. Intended to be passed directly to `rope()` or `describe_posterior()`. ```r library(bayestestr) # Linear model ROPE lm_model <- lm(mpg ~ wt + cyl, data = mtcars) rope_range(lm_model) # [1] -0.912 0.912 (≈ ±0.1 * SD(mpg)) # Logistic model ROPE glm_model <- glm(vs ~ mpg + hp, data = mtcars, family = binomial) rope_range(glm_model) # [1] -0.18 0.18 # Use automatically in rope() on a Bayesian model # model <- rstanarm::stan_glm(mpg ~ wt + cyl, data = mtcars, refresh = 0) # rope(model, range = rope_range(model)) # rope(model) # rope_range() is called automatically when range = "default" ``` ``` -------------------------------- ### Extract MCMC sampling diagnostics Source: https://context7.com/easystats/bayestestr/llms.txt Extracts sampling diagnostics like Effective Sample Size (ESS), Rhat (convergence), and Monte Carlo Standard Error (MCSE) from MCMC chains. ESS should ideally exceed 1000, and Rhat should be ≤ 1.01. ```r library(bayestestR) # Diagnostics from raw MCMC chain lists set.seed(101) chains <- replicate( 4, as.data.frame(replicate(3, rnorm(1000))), simplify = FALSE ) names(chains) <- NULL for (i in seq_along(chains)) colnames(chains[[i]]) <- c("alpha", "beta", "sigma") diagnostic_posterior(chains, diagnostic = "all") # Parameter | ESS | ESS_bulk | Rhat | MCSE # ------------------------------------------- # alpha | 989 | 1002 | 1.000 | 0.032 # beta | 997 | 998 | 0.999 | 0.032 # sigma | 985 | 994 | 1.001 | 0.031 ``` -------------------------------- ### Compute Region of Practical Equivalence (ROPE) Source: https://context7.com/easystats/bayestestr/llms.txt Calculates the proportion of a posterior's credible interval that falls within a specified Region of Practical Equivalence (ROPE). Use `complement = TRUE` to also retrieve proportions outside the ROPE. Can be applied to numeric vectors or model objects. ```r library(bayestestR) # Nearly-null effect — most of posterior inside ROPE posterior_null <- rnorm(10000, mean = 0.0, sd = 0.05) rope(posterior_null, range = c(-0.1, 0.1)) # # Proportion of samples inside the ROPE [-0.10, 0.10]: # Inside ROPE: 95.24% # Clear positive effect — very little inside ROPE posterior_effect <- rnorm(10000, mean = 0.5, sd = 0.2) rope(posterior_effect, range = c(-0.1, 0.1), ci = 0.95) # Inside ROPE: 1.03% # Multiple CI levels + complementary probabilities rope( posterior_effect, range = c(-0.1, 0.1), ci = c(0.89, 0.95), complement = TRUE ) # CI | ROPE_low | ROPE_high | ROPE_Percentage | Superiority_Percentage # 0.89 | -0.10 | 0.10 | 0.91 | 99.09 # 0.95 | -0.10 | 0.10 | 1.03 | 98.97 # Model with named per-parameter ROPE ranges # model <- rstanarm::stan_glm(mpg ~ wt + gear, data = mtcars, refresh = 0) # rope(model, range = list(wt = c(-0.5, 0.5), gear = c(-1, 1))) ``` -------------------------------- ### Compute Highest Density Interval (HDI) and Equal-Tailed Interval (ETI) Source: https://github.com/easystats/bayestestr/blob/main/README.md Calculate the Highest Density Interval (HDI) and Equal-Tailed Interval (ETI) for a posterior distribution using `hdi()` and `eti()` respectively. HDI is preferred for Bayesian credible intervals as it always includes the mode. ```r posterior <- distribution_chisquared(10000, 4) hdi(posterior) eti(posterior) ``` -------------------------------- ### Compute Bayes Factors for Model Comparison Source: https://context7.com/easystats/bayestestr/llms.txt Compares multiple fitted models by computing Bayes Factors relative to a denominator model. Supports lm/glm (via BIC approximation), stanreg/brmsfit (via bridge sampling), and BFBayesFactor objects. Use for selecting the best-fitting model. ```r library(bayestestR) # Linear model comparison via BIC approximation lm0 <- lm(mpg ~ 1, data = mtcars) lm1 <- lm(mpg ~ hp, data = mtcars) lm2 <- lm(mpg ~ hp + drat, data = mtcars) lm3 <- lm(mpg ~ hp * drat, data = mtcars) (BFM <- bayesfactor_models(lm1, lm2, lm3, denominator = lm0)) # Bayes Factors for Model Comparison # Model | BF # ------------------- # hp | 1.616 # hp + drat | 11.826 # hp * drat | 4.077 # * Against Denominator: mpg ~ 1 ``` ```r # Re-reference to the best model update(BFM, reference = "top") ``` ```r # Full comparison matrix as.matrix(BFM) ``` ```r # Inclusion Bayes factors: which predictors are supported across all models? bayesfactor_inclusion(BFM) # Term | P(prior) | P(posterior) | log(BF) | BF # ---------------------------------------------------- # hp | 0.75 | 0.97 | 2.00 | 7.38 # drat | 0.50 | 0.71 | 1.23 | 3.41 # hp:drat | 0.25 | 0.19 | -0.27 | 0.76 ``` -------------------------------- ### bayesfactor_models Source: https://context7.com/easystats/bayestestr/llms.txt Compares multiple fitted models by computing Bayes factors relative to a denominator model. Supports various model types and provides options for referencing and inclusion analysis. ```APIDOC ## bayesfactor_models() — Bayes Factor for Model Comparison ### Description Compares multiple fitted models by computing **Bayes factors** relative to a denominator model. Supports `lm`/`glm` (via BIC approximation), `stanreg`/`brmsfit` (via bridge sampling), and `BFBayesFactor` objects. Use `bayesfactor_inclusion()` for variable-level averaging across models. ### Method `bayesfactor_models(..., denominator)` ### Parameters - **...**: Multiple model objects to compare. - **denominator**: The model to use as the denominator for the Bayes Factor calculation. ### Request Example ```r library(bayestestR) # Linear model comparison via BIC approximation lm0 <- lm(mpg ~ 1, data = mtcars) lm1 <- lm(mpg ~ hp, data = mtcars) lm2 <- lm(mpg ~ hp + drat, data = mtcars) lm3 <- lm(mpg ~ hp * drat, data = mtcars) (BFM <- bayesfactor_models(lm1, lm2, lm3, denominator = lm0)) ``` ### Response Returns a Bayes Factor for Models object with methods for updating, printing, and conversion to matrices. #### Success Response (BFM object) - **Model** (string): Name of the model. - **BF** (numeric): The calculated Bayes Factor relative to the denominator. #### Response Example ``` # Bayes Factors for Model Comparison # Model | BF # ------------------- # hp | 1.616 # hp + drat | 11.826 # hp * drat | 4.077 # * Against Denominator: mpg ~ 1 ``` ### Additional Examples ```r # Re-reference to the best model update(BFM, reference = "top") # Full comparison matrix as.matrix(BFM) # Inclusion Bayes factors: which predictors are supported across all models? bayesfactor_inclusion(BFM) ``` ``` -------------------------------- ### Implement HDI+ROPE Decision Rule Source: https://context7.com/easystats/bayestestr/llms.txt Applies Kruschke's HDI+ROPE decision rule to classify parameters as 'rejected', 'accepted', or 'undecided' based on the relationship between the 95% HDI and the ROPE. This provides a Bayesian analogue to NHST. Works with numeric vectors or model objects. ```r library(bayestestR) # Rejected: HDI entirely outside ROPE equivalence_test(rnorm(1000, mean = 1.0, sd = 0.2), range = c(-0.1, 0.1)) # ROPE: [-0.10, 0.10] # Parameter | H0 | % in ROPE | 95% HDI # ------------------------------------------------- # Posterior | Rejected | 0.00 | [ 0.61, 1.39] # Accepted: HDI entirely inside ROPE equivalence_test(rnorm(1000, mean = 0.0, sd = 0.02), range = c(-0.1, 0.1)) # H0: Accepted — all credible values are negligible # Undecided: partial overlap equivalence_test(rnorm(1000, mean = 0.07, sd = 0.08), range = c(-0.1, 0.1)) # H0: Undecided # Model-based (rstanarm) # model <- rstanarm::stan_glm(mpg ~ wt + cyl, data = mtcars, refresh = 0) # equivalence_test(model) ``` -------------------------------- ### Compute ROPE range for linear and logistic models Source: https://context7.com/easystats/bayestestr/llms.txt Automatically computes ROPE bounds based on the model's response type. For linear models, it uses ±0.1 * SD(y); for logistic models, it uses ±0.18. This is intended for direct use with `rope()` or `describe_posterior()`. ```r library(bayestestR) # Linear model ROPE lm_model <- lm(mpg ~ wt + cyl, data = mtcars) rope_range(lm_model) # [1] -0.912 0.912 (≈ ±0.1 * SD(mpg)) # Logistic model ROPE glm_model <- glm(vs ~ mpg + hp, data = mtcars, family = binomial) rope_range(glm_model) # [1] -0.18 0.18 ``` -------------------------------- ### Calculate Various Point Estimates from Posterior Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Use `point_estimate()` to compute the median, mean, or MAP estimate from a posterior distribution. Specify the desired `centrality` argument. ```r point_estimate(posterior) ``` ```r point_estimate(posterior, centrality = "mean") ``` ```r point_estimate(posterior, centrality = "map") ``` -------------------------------- ### Calculate Highest Density Interval (HDI) Source: https://github.com/easystats/bayestestr/blob/main/paper/JOSS paper files/paper.md Compute the Highest Density Interval (HDI) of a posterior distribution using `hdi()`. By default, it returns the 89% interval. ```r hdi(posterior) ```