### Install brms Development Version from GitHub Source: https://github.com/paul-buerkner/brms/blob/master/README.md Install the latest developmental version of brms directly from GitHub. Ensure the 'remotes' package is installed first if you don't have it. ```r if (!requireNamespace("remotes")) { install.packages("remotes") } remotes::install_github("paul-buerkner/brms") ``` -------------------------------- ### Basic BRMS Phylogenetic Model Setup Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html This snippet shows the basic setup for a phylogenetic generalized linear mixed-effects model using BRMS. It requires the 'brms' and 'ape' packages and a phylogenetic tree object. ```R library(brms) library(ape) # Load your phylogenetic tree (e.g., from a Nexus file) tree <- read.nexus("path/to/your/tree.nex") # Define your model formula (replace with your actual model) # Example: a simple linear model with a phylogenetic random effect formula <- bf(trait ~ 1 + predictor + (1 | gr(phylo, cov = V)), sigma ~ 1 + predictor, family = gaussian()) # Fit the model fit <- brm(formula, data = your_data, data2 = list(V = vcv(tree)), prior = c(prior("normal(0, 1)", class = "b"), prior("cauchy(0, 1)", class = "sd"), prior("normal(0, 1)", class = "Intercept"), prior("normal(0, 1)", class = "sigma"))) ``` -------------------------------- ### BRMS Threading Example Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html This is a general example related to BRMS threading. It might demonstrate a specific pattern or utility function used for managing threads. ```java public class BrmsThreading { public static void main(String[] args) { // Example of creating and starting a thread Thread thread = new Thread(() -> { System.out.println("Thread is running..."); // Thread logic here }); thread.start(); try { // Wait for the thread to finish thread.join(); System.out.println("Thread finished."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.err.println("Thread interrupted: " + e.getMessage()); } } } ``` -------------------------------- ### BRMS Synchronization Example Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html Demonstrates synchronization mechanisms used in BRMS to prevent race conditions and ensure data consistency between threads. ```java public class BrmsSynchronization { private int counter = 0; public synchronized void incrementCounter() { counter++; System.out.println(Thread.currentThread().getName() + " incremented counter to " + counter); } public static void main(String[] args) { BrmsSynchronization sync = new BrmsSynchronization(); Thread t1 = new Thread(() -> { for (int i = 0; i < 5; i++) { sync.incrementCounter(); } }, "Thread-1"); Thread t2 = new Thread(() -> { for (int i = 0; i < 5; i++) { sync.incrementCounter(); } }, "Thread-2"); t1.start(); t2.start(); } } ``` -------------------------------- ### Nonlinear Model Example (Gompertz Growth) Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a Gompertz growth model. This model is also used for growth curves but has a different shape compared to logistic growth. ```R fit_gompertz <- brm( bf(y ~ a * exp(-b * exp(-c * x))), data = df_gompertz, family = gaussian(), prior = c( prior("normal", nlpar = "a"), prior("normal", nlpar = "b"), prior("normal", nlpar = "c") ), chains = 4, iter = 2000, cores = 4 ) ``` -------------------------------- ### Nonlinear Model Example (Michaelis-Menten Kinetics) Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a Michaelis-Menten model, commonly used in enzyme kinetics. It describes the rate of enzymatic reactions. ```R fit_michaelis_menten <- brm( bf(y ~ (Vmax * x) / (Km + x)), data = df_mm, family = gaussian(), prior = c( prior("normal", nlpar = "Vmax"), prior("normal", nlpar = "Km") ), chains = 4, iter = 2000, cores = 4 ) ``` -------------------------------- ### Nonlinear Model Example (Logistic Growth) Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a logistic growth model. This model is suitable for data that exhibits an S-shaped growth curve. ```R fit_logistic <- brm( bf(y ~ a / (1 + exp(-(b * (x - c))))), data = df_logistic, family = gaussian(), prior = c( prior("normal", nlpar = "a"), prior("normal", nlpar = "b"), prior("normal", nlpar = "c") ), chains = 4, iter = 2000, cores = 4 ) ``` -------------------------------- ### Model Comparison with Different Phylogenetic Structures Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html This example shows how to compare models with different phylogenetic structures (e.g., Brownian motion vs. Pagel's lambda) using information criteria like LOO or WAIC. ```R # Fit a model with Brownian motion (default if V is provided) fit_bm <- brm(bf(trait ~ 1 + predictor + (1 | gr(phylo, cov = V))), data = your_data, data2 = list(V = vcv(tree)), family = gaussian()) # Fit a model with Pagel's lambda fit_lambda <- brm(bf(trait ~ 1 + predictor + (1 | pagel(phylo, cov = V))), data = your_data, data2 = list(V = vcv(tree)), family = gaussian()) # Compare models using LOO cross-validation loo_bm <- loo(fit_bm) loo_lambda <- loo(fit_lambda) # Print comparison print(loo_bm) print(loo_lambda) # Or use a comparison function # compare(fit_bm, fit_lambda) ``` -------------------------------- ### Fit a Simple BRMS Model Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html This snippet demonstrates how to fit a basic Bayesian regression model using the brms package. Ensure the 'brms' package is installed and loaded. ```R library(brms) simple_model <- brm(Y ~ X + (1|group), data = data) ``` -------------------------------- ### Multilevel Poisson Model with BRMS Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html Example of fitting a multilevel Poisson model using brms. This snippet demonstrates setting up priors, specifying the family, and configuring threading for parallel execution. ```R model_poisson <- brm( y ~ 1 + x1 + x2 + (1 | g), data = fake, family = poisson(), iter = 500, # short sampling to speedup example chains = 2, prior = prior(normal(0,1), class = b) + prior(constant(1), class = sd, group = g), backend = "cmdstanr", threads = threading(4) ) ``` -------------------------------- ### Load Phylogenetic Data and Prepare Covariance Matrix Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html Loads a phylogenetic tree and associated data, then computes the phylogenetic covariance matrix. Ensure the 'ape' package is installed. ```r phylo <- ape::read.nexus("https://paul-buerkner.github.io/data/phylo.nex") data_simple <- read.table( "https://paul-buerkner.github.io/data/data_simple.txt", header = TRUE ) head(data_simple) A <- ape::vcv.phylo(phylo) ``` -------------------------------- ### Fit a nonlinear model with a logistic growth function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a nonlinear model using the logistic growth function. This is useful for modeling processes that exhibit saturation. ```R brms_nl_logistic <- brm( Y ~ nlf(a / (1 + exp(-(b + c * X))), nlpars = c(a, b, c)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Fit a nonlinear model with a power law function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a nonlinear model using a power law function. This is suitable for relationships where one variable scales with a power of another. ```R brms_nl_power_law <- brm( Y ~ nl(a * X^b, nlpars = c(a, b)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Install brms from CRAN Source: https://github.com/paul-buerkner/brms/blob/master/README.md Use this command to install the latest stable release of the brms package from the Comprehensive R Archive Network (CRAN). ```r install.packages("brms") ``` -------------------------------- ### Load and Inspect BTdata Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_multivariate.html Loads the BTdata dataset and displays the first few rows to show its structure. ```r data("BTdata", package = "MCMCglmm") head(BTdata) ``` -------------------------------- ### Benchmark Threading Configuration Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html Configures chunking for benchmarking threading performance by calculating grainsize based on the number of chunks. Uses a small number of iterations for quick testing. ```r chunking_bench <- transform( data.frame(chunks = 4^(0:3)), grainsize = ceiling(N / chunks) ) iter_test <- c(10, 20, 40) # very short test runs scaling_chunking <- benchmark_threading( model_poisson, cores = 1, grainsize = chunking_bench$grainsize, # test various grainsizes iter = iter_test, static = TRUE # with static partitioner ) # run as reference the model *without* reduce_sum ref <- benchmark_reference(model_poisson, iter_test) # for additional data munging please refer to the appendix ``` -------------------------------- ### Plotting Model Fit with Regex Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_missings.html Use this snippet to visualize the convergence of model parameters, specifically focusing on parameters matching a regular expression. This is useful for diagnosing potential convergence issues. ```R plot(fit_imp1, variable = "^b", regex = TRUE) ``` -------------------------------- ### Multivariate Normal Distribution Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_multivariate.html Example of defining and sampling from a multivariate normal distribution. ```R library(brms) # Define a multivariate normal distribution # mu: mean vector # Sigma: covariance matrix mu <- c(0, 0) Sigma <- matrix(c(1, 0.5, 0.5, 1), nrow = 2) # Sample from the distribution set.seed(123) nsamples <- 1000 posterior_samples <- rmvnorm(n = nsamples, mean = mu, sigma = Sigma) # Plot the samples (optional) plot(posterior_samples, pch = '.', xlab = 'X1', ylab = 'X2') ``` -------------------------------- ### Fit a nonlinear model with a log-logistic function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a nonlinear model using the log-logistic function. This is a common choice for dose-response curves. ```R brms_nl_log_logistic <- brm( Y ~ nl(a / (1 + exp(-(b + c * log(X)))), nlpars = c(a, b, c)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Add City Identifier and City-Related Variation Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_monotonic.html Adds a 'city' identifier to the data and introduces city-specific variation to the 'ls' variable. This setup is for multilevel modeling. ```R dat$city <- rep(1:10, each = 10) var_city <- rnorm(10, sd = 10) dat$ls <- dat$ls + var_city[dat$city] ``` -------------------------------- ### Running a BRMS model serially Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html This snippet shows how to run a BRMS model serially using the cmdstanr backend. It serves as a baseline for comparison when implementing parallelization. ```R fit_serial <- brm( count ~ zAge + zBase * Trt + (1|patient), data = epilepsy, family = poisson(), chains = 4, cores = 4, backend = "cmdstanr" ) ``` -------------------------------- ### Fit a nonlinear model with a von Bertalanffy growth function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Demonstrates fitting a nonlinear model using the von Bertalanffy growth function, commonly used in fisheries science to model fish growth. ```R brms_nl_von_bertalanffy <- brm( Y ~ nl(a * (1 - exp(-b * (X - c))), nlpars = c(a, b, c)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Fit a nonlinear model with a linear function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Example of fitting a nonlinear model using a simple linear function. This can be used as a baseline or when the relationship is approximately linear. ```R brms_nl_linear <- brm( Y ~ nl(a + b * X, nlpars = c(a, b)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Load and Prepare Fisher's z Data for Meta-Analysis Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html Loads Fisher's z-transformed correlation coefficients and sample sizes from a URL and prepares the data for a meta-analytic model. It adds an observation index and calculates the sampling variance. ```R data_fisher <- read.table( "https://paul-buerkner.github.io/data/data_effect.txt", header = TRUE ) data_fisher$obs <- 1:nrow(data_fisher) head(data_fisher) ``` -------------------------------- ### Fit a nonlinear model with a Gompertz growth function Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Demonstrates fitting a nonlinear model using the Gompertz growth function. This function is often used in growth studies. ```R brms_nl_gompertz <- brm( Y ~ nlf(a * exp(-b * exp(c * X)), nlpars = c(a, b, c)), data = data_nl, family = gaussian() ) ``` -------------------------------- ### Bayesian Phylogenetic Tree Inference Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_phylogenetics.html Example of inferring a phylogenetic tree using BRMS. Requires the 'brms' and 'ape' packages. Ensure your data is in a format compatible with phylogenetic analysis. ```R library(brms) library(ape) # Assuming 'phylo_data' is a phylogenetic tree object (e.g., from ape) # and 'response_variable' is your trait data # Define the phylogenetic generalized linear mixed-effects model # formula: response_variable ~ predictor_variable + (1 | gr(phylo_nodes, cov = phylo_cor)) # where phylo_nodes and phylo_cor are derived from the phylogenetic tree # Example formula structure (replace with your actual variables and tree structure) # model_formula <- bf(response_variable ~ predictor_variable, # sigma ~ gr(phylo_nodes, cov = phylo_cor)) # Fit the model # fit <- brm(model_formula, data = your_data_frame, family = gaussian(), # data2 = list(phylo_cor = vcv(phylo_data))) # For demonstration, a placeholder model structure: fit <- brm(bf(y ~ x + (1 | gr(node, cov = C))), data = data.frame(y = rnorm(10), x = rnorm(10)), data2 = list(C = diag(10)), family = gaussian(), cores = 4) summary(fit) plot(fit) ``` -------------------------------- ### Fit Custom Beta-Binomial Model Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_customfamilies.html Fits a brms model using the custom beta-binomial family. This example demonstrates how to specify the custom family and Stan variables when fitting the model. ```R fit2 <- brm( incidence | vint(size) ~ period + (1|herd), data = cbpp, family = beta_binomial2, stanvars = stanvars ) ``` -------------------------------- ### Fit Non-linear Model Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_nonlinear.html Fit a non-linear model using brms. This is useful for capturing complex relationships between variables where a linear model is insufficient. Ensure the brms package is installed and loaded. ```R fit1 <- brm(bf(y ~ x, nl = TRUE), data = dat1) ``` -------------------------------- ### MathJax Initialization Script Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_threading.html This JavaScript snippet dynamically loads the MathJax library, which is used for rendering mathematical formulas in web pages. It appends the script tag to the document's head. ```javascript (function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"; document.getElementsByTagName("head")[0].appendChild(script); })(); ``` -------------------------------- ### Update Fitted brms Model Without Recompilation Source: https://github.com/paul-buerkner/brms/blob/master/README.md Use the `update` method on an existing fitted brms model object to rerun it, for example with more draws, without recompiling the Stan code. ```r # Assuming 'fit' is a fitted brms model object update(fit) ``` -------------------------------- ### Fit Multivariate Model and Summarize Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_multivariate.html Fits the defined multivariate model using brm, adds the 'loo' criterion, and prints a summary of the results. ```r fit1 <- brm(bform1, data = BTdata, chains = 2, cores = 2) fit1 <- add_criterion(fit1, "loo") summary(fit1) ``` -------------------------------- ### Load and Inspect NHANES Data Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_missings.html Loads the NHANES dataset from the 'mice' package and displays the first few rows to show the structure and presence of missing values. ```r data("nhanes", package = "mice") head(nhanes) ``` -------------------------------- ### Fit Multilevel Model with Monotonic Effects Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_monotonic.html Fits a multilevel model using brms, allowing the intercept and the monotonic effect of income to vary by city. Ensure the brms package is installed and loaded. ```R fit6 <- brm(ls ~ mo(income)*age + (mo(income) | city), data = dat) ``` -------------------------------- ### Simulate Data for Smooth Term Analysis Source: https://github.com/paul-buerkner/brms/blob/master/doc/brms_distreg.html Simulates data suitable for analyzing smooth terms in regression models using the mgcv package. ```r dat_smooth <- mgcv::gamSim(eg = 6, n = 200, scale = 2, verbose = FALSE) ```