| Type: | Package |
| Title: | Bayesian Analysis of Networks of Binary and/or Ordinal Variables |
| Version: | 0.1.6.1 |
| Date: | 2025-10-03 |
| Maintainer: | Maarten Marsman <m.marsman@uva.nl> |
| Description: | Bayesian variable selection methods for analyzing the structure of a Markov random field model for a network of binary and/or ordinal variables. |
| Copyright: | Includes datasets 'ADHD' and 'Boredom', which are licensedunder CC-BY 4. See individual data documentation for licenseand citation. |
| License: | GPL-2 |GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://Bayesian-Graphical-Modelling-Lab.github.io/bgms/ |
| BugReports: | https://github.com/Bayesian-Graphical-Modelling-Lab/bgms/issues |
| Imports: | Rcpp (≥ 1.0.7), RcppParallel, Rdpack, methods, coda,lifecycle |
| RdMacros: | Rdpack |
| LinkingTo: | Rcpp, RcppArmadillo, RcppParallel, dqrng, BH |
| RoxygenNote: | 7.3.3 |
| Depends: | R (≥ 3.5) |
| LazyData: | true |
| Encoding: | UTF-8 |
| Suggests: | ggplot2, knitr, parallel, qgraph, rmarkdown, testthat (≥3.0.0) |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Config/Needs/website: | tidyverse/tidytemplate |
| NeedsCompilation: | yes |
| Packaged: | 2025-10-03 12:54:27 UTC; maartenmarsman |
| Author: | Maarten Marsman |
| Repository: | CRAN |
| Date/Publication: | 2025-10-04 09:20:02 UTC |
bgms: Bayesian Analysis of Networks of Binary and/or Ordinal Variables
Description
TheR packagebgms provides tools for Bayesian analysis ofthe ordinal Markov random field (MRF), a graphical model describing networksof binary and/or ordinal variables (Marsman et al. 2025).The likelihood is approximated via a pseudolikelihood, and Markov chain MonteCarlo (MCMC) methods are used to sample from the corresponding pseudoposteriordistribution of model parameters.
The main entry points are:
bgm: estimation in a one-sample design.
bgmCompare: estimation and group comparison in anindependent-sample design.
Both functions support Bayesian effect selection with spike-and-slab priors.
In one-sample designs,
bgmmodels the presence or absence ofedges between variables. Posterior inclusion probabilities quantify theplausibility of each edge and can be converted into Bayes factors forconditional independence tests.bgmcan also model communities (clusters) of variables. Theposterior distribution of the number of clusters provides evidence for oragainst clustering (Sekulovski et al. 2025).In independent-sample designs,
bgmCompareestimates groupdifferences in edge weights and category thresholds. Posterior inclusionprobabilities quantify the evidence for differences and can be convertedinto Bayes factors for parameter equivalence tests(Marsman et al. 2024).
Tools
The package also provides:
Simulation of response data from MRFs with a Gibbs sampler(
mrfSampler).Posterior estimation and edge selection in one-sample designs(
bgm).Posterior estimation and group-difference selection inindependent-sample designs (
bgmCompare).
Vignettes
For tutorials and worked examples, see:
vignette("intro", package = "bgms")— Getting started.vignette("comparison", package = "bgms")— Model comparison.vignette("diagnostics", package = "bgms")— Diagnostics andspike-and-slab summaries.
Author(s)
Maintainer: Maarten Marsmanm.marsman@uva.nl (ORCID)
Other contributors:
Giuseppe Arena (ORCID) [contributor]
Karoline Huth (ORCID) [contributor]
Nikola Sekulovski (ORCID) [contributor]
Don van den Bergh (ORCID) [contributor]
References
Marsman M, Waldorp LJ, Sekulovski N, Haslbeck JMB (2024).“Bayes factor tests for group differences in ordinal and binary graphical models.”Retrieved from https://osf.io/preprints/osf/f4pk9.OSF preprint.
Marsman M, van den Bergh D, Haslbeck JMB (2025).“Bayesian analysis of the ordinal Markov random field.”Psychometrika,90, 146–-182.
Sekulovski N, Arena G, Haslbeck JMB, Huth KBS, Friel N, Marsman M (2025).“A Stochastic Block Prior for Clustering in Graphical Models.”Retrieved fromhttps://osf.io/preprints/psyarxiv/29p3m_v1.OSF preprint.
See Also
Useful links:
ADHD Symptom Checklist for Children Aged 6–8 Years
Description
This dataset includes ADHD symptom ratings for 355 children aged 6 to 8 years from theChildren’s Attention Project (CAP) cohort (Silk et al. 2019). The sampleconsists of 146 children diagnosed with ADHD and 209 without a diagnosis. Symptoms wereassessed through structured interviews with parents using the NIMH Diagnostic InterviewSchedule for Children IV (DISC-IV) (Shaffer et al. 2000). The checklistincludes 18 items: 9 Inattentive (I) and 9 Hyperactive/Impulsive (HI). Each item is binary(1 = present, 0 = absent).
Usage
data("ADHD")Format
A matrix with 355 rows and 19 columns.
- group
ADHD diagnosis: 1 = diagnosed, 0 = not diagnosed
- avoid
Often avoids, dislikes, or is reluctant to engage in tasksthat require sustained mental effort (I)
- closeatt
Often fails to give close attention to details or makescareless mistakes in schoolwork, work, or other activities (I)
- distract
Is often easily distracted by extraneous stimuli (I)
- forget
Is often forgetful in daily activities (I)
- instruct
Often does not follow through on instructions and fails tofinish schoolwork, chores, or duties in the workplace (I)
- listen
Often does not seem to listen when spoken to directly(I)
- loses
Often loses things necessary for tasks or activities (I)
- org
Often has difficulty organizing tasks and activities (I)
- susatt
Often has difficulty sustaining attention in tasks or playactivities (I)
- blurts
Often blurts out answers before questions have been completed(HI)
- fidget
Often fidgets with hands or feet or squirms in seat(HI)
- interrupt
Often interrupts or intrudes on others (HI)
- motor
Is often "on the go" or often acts as if "driven by a motor"(HI)
- quiet
Often has difficulty playing or engaging in leisure activitiesquietly (HI)
- runs
Often runs about or climbs excessively in situations in whichit is inappropriate (HI)
- seat
Often leaves seat in classroom or in other situations in whichremaining seated is expected (HI)
- talks
Often talks excessively (HI)
- turn
Often has difficulty awaiting turn (HI)
Source
Silk et al. (2019).Data retrieved fromdoi:10.1371/journal.pone.0211053.s004.Licensed under the CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
References
Shaffer D, Fisher P, Lucas CP, Dulcan MK, Schwab-Stone ME (2000).“NIMH Diagnostic Interview Schedule for Children Version IV (NIMH DISC-IV): description, differences from previous versions, and reliability of some common diagnoses.”Journal of the American Academy of Child & Adolescent Psychiatry,39, 28–38.doi:10.1097/00004583-200001000-00014, PMID: 10638065.
Silk TJ, Malpas CB, Beare R, Efron D, Anderson V, Hazell P, Jongeling B, Nicholson JM, Sciberras E (2019).“A network analysis approach to ADHD symptoms: More than the sum of its parts.”PLOS ONE,14(1), e0211053.doi:10.1371/journal.pone.0211053.
Short Boredom Proneness Scale Responses
Description
This dataset includes responses to the 8-item Short Boredom Proneness Scale (SBPS),a self-report measure of an individual's susceptibility to boredom(Martarelli et al. 2023). Items were rated on a 7-point Likert scaleranging from 1 ("strongly disagree") to 7 ("strongly agree"). The scale was administeredin either English (Struk et al. 2015) or French (translated by (Martarelli et al. 2023)).
Usage
data("Boredom")Format
A matrix with 986 rows and 9 columns. Each row corresponds to a respondent.
- language
Language in which the SBPS was administered: "en" = English, "fr" = French
- loose_ends
I often find myself at “loose ends,” not knowing what todo.
- entertain
I find it hard to entertain myself.
- repetitive
Many things I have to do are repetitive and monotonous.
- stimulation
It takes more stimulation to get me going than mostpeople.
- motivated
I don't feel motivated by most things that I do.
- keep_interest
In most situations, it is hard for me to findsomething to do or see to keep me interested.
- sit_around
Much of the time, I just sit around doing nothing.
- half_dead_dull
Unless I am doing something exciting, even dangerous,I feel half-dead and dull.
Source
Martarelli et al. (2023).Data retrieved fromhttps://osf.io/qhux8.Licensed under the CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
References
Martarelli CS, Baillifard A, Audrin C (2023).“A Trait-Based Network Perspective on the Validation of the French Short Boredom Proneness Scale.”European Journal of Psychological Assessment,39(6), 390–399.doi:10.1027/1015-5759/a000718.
Struk AA, Carriere JSA, Cheyne JA, Danckert J (2015).“A Short Boredom Proneness Scale: Development and Psychometric Properties.”Assessment,24(3), 346–359.doi:10.1177/1073191115609996.
PTSD Symptoms in Wenchuan Earthquake Survivors Who Lost a Child
Description
This dataset contains responses to 17 items assessing symptoms of post-traumatic stress disorder (PTSD)in Chinese adults who survived the 2008 Wenchuan earthquake and lost at least one child in the disaster(McNally et al. 2015). Participants completed the civilian version of the Posttraumatic Checklist,with each item corresponding to a DSM-IV PTSD symptom. Items were rated on a 5-point Likert scale from"not at all" to "extremely," indicating the degree to which the symptom bothered the respondent in thepast month.
Usage
data("Wenchuan")Format
A matrix with 362 rows and 17 columns. Each row represents a participant.
- intrusion
Repeated, disturbing memories, thoughts, or images of astressful experience from the past?
- dreams
Repeated, disturbing dreams of a stressful experience fromthe past?
- flash
Suddenly acting or feeling as if a stressful experience werehappening again (as if you were reliving it)?
- upset
Feeling very upset when something reminded you of a stressfulexperience from the past?
- physior
Having physical reactions (e.g., heart pounding, troublebreathing, sweating) when something reminded you of a stressful experiencefrom the past?
- avoidth
Avoiding thinking about or talking about a stressfulexperience from the past or avoiding having feelings related to it?
- avoidact
Avoiding activities or situations because they reminded youof a stressful experience from the past?
- amnesia
Trouble remembering important parts of a stressfulexperience from the past?
- lossint
Loss of interest in activities that you used to enjoy?
- distant
Feeling distant or cut off from other people?
- numb
Feeling emotionally numb or being unable to have lovingfeelings for those close to you?
- future
Feeling as if your future will somehow be cut short?
- sleep
Trouble falling or staying asleep?
- anger
Feeling irritable or having angry outbursts?
- concen
Having difficulty concentrating?
- hyper
Being "super-alert" or watchful or on guard?
- startle
Feeling jumpy or easily startled?
Source
https://psychosystems.org/wp-content/uploads/2014/10/Wenchuan.csv
References
McNally RJ, Robinaugh DJ, Wu GWY, Wang L, Deserno MK, Borsboom D (2015).“Mental disorders as causal systems: A network approach to posttraumatic stress disorder.”Clinical Psychological Science,6, 836–849.doi:10.1177/2167702614553230.
Bayesian Estimation or Edge Selection for Markov Random Fields
Description
Thebgm function estimates the pseudoposterior distribution ofcategory thresholds (main effects) and pairwise interaction parameters of aMarkov Random Field (MRF) model for binary and/or ordinal variables.Optionally, it performs Bayesian edge selection using spike-and-slabpriors to infer the network structure.
Usage
bgm( x, variable_type = "ordinal", baseline_category, iter = 1000, warmup = 1000, pairwise_scale = 2.5, main_alpha = 0.5, main_beta = 0.5, edge_selection = TRUE, edge_prior = c("Bernoulli", "Beta-Bernoulli", "Stochastic-Block"), inclusion_probability = 0.5, beta_bernoulli_alpha = 1, beta_bernoulli_beta = 1, dirichlet_alpha = 1, lambda = 1, na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis", "hamiltonian-mc"), target_accept, hmc_num_leapfrogs = 100, nuts_max_depth = 10, learn_mass_matrix = FALSE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, interaction_scale, burnin, save, threshold_alpha, threshold_beta)Arguments
x | A data frame or matrix with |
variable_type | Character or character vector. Specifies the type ofeach variable in |
baseline_category | Integer or vector. Baseline category used inBlume–Capel variables. Can be a single integer (applied to all) or avector of length |
iter | Integer. Number of post–burn-in iterations (per chain).Default: |
warmup | Integer. Number of warmup iterations before collectingsamples. A minimum of 1000 iterations is enforced, with a warning if asmaller value is requested. Default: |
pairwise_scale | Double. Scale of the Cauchy prior for pairwiseinteraction parameters. Default: |
main_alpha,main_beta | Double. Shape parameters of thebeta-prime prior for threshold parameters. Must be positive. If equal,the prior is symmetric. Defaults: |
edge_selection | Logical. Whether to perform Bayesian edge selection.If |
edge_prior | Character. Specifies the prior for edge inclusion.Options: |
inclusion_probability | Numeric scalar. Prior inclusion probabilityof each edge (used with the Bernoulli prior). Default: |
beta_bernoulli_alpha,beta_bernoulli_beta | Double. Shape parametersfor the beta distribution in the Beta–Bernoulli and the Stochastic-Blockpriors. Must be positive. Defaults: |
dirichlet_alpha | Double. Concentration parameter of the Dirichletprior on block assignments (used with the Stochastic Block model).Default: |
lambda | Double. Rate of the zero-truncated Poisson prior on thenumber of clusters in the Stochastic Block Model. Default: |
na_action | Character. Specifies missing data handling. Either |
update_method | Character. Specifies how the MCMC sampler updatesthe model parameters:
Default: |
target_accept | Numeric between 0 and 1. Target acceptance rate forthe sampler. Defaults are set automatically if not supplied: |
hmc_num_leapfrogs | Integer. Number of leapfrog steps for HamiltonianMonte Carlo. Must be positive. Default: |
nuts_max_depth | Integer. Maximum tree depth in NUTS. Must be positive.Default: |
learn_mass_matrix | Logical. If |
chains | Integer. Number of parallel chains to run. Default: |
cores | Integer. Number of CPU cores for parallel execution.Default: |
display_progress | Logical. Whether to show a progress bar duringsampling. Default: |
seed | Optional integer. Random seed for reproducibility. Must be asingle non-negative integer. |
interaction_scale,burnin,save,threshold_alpha,threshold_beta | 'r lifecycle::badge("deprecated")'Deprecated arguments as of **bgms 0.1.6.0**.Use 'pairwise_scale', 'warmup', 'main_alpha', and 'main_beta' instead. |
Details
This function models the joint distribution of binary and ordinal variablesusing a Markov Random Field, with support for edge selection through Bayesianvariable selection. The statistical foundation of the model is described inMarsman et al. (2025), where the ordinalMRF model and its Bayesian estimation procedure were first introduced. Whilethe implementation inbgms has since been extended and updated (e.g.,alternative priors, parallel chains, HMC/NUTS warmup), it builds on thatoriginal framework.
Key components of the model are described in the sections below.
Value
A list of class"bgms" with posterior summaries, posterior meanmatrices, and access to raw MCMC draws. The object can be passed toprint(),summary(), andcoef().
Main components include:
posterior_summary_main: Data frame with posterior summaries(mean, sd, MCSE, ESS, Rhat) for category threshold parameters.posterior_summary_pairwise: Data frame with posteriorsummaries for pairwise interaction parameters.posterior_summary_indicator: Data frame with posteriorsummaries for edge inclusion indicators (ifedge_selection = TRUE).posterior_mean_main: Matrix of posterior mean thresholds(rows = variables, cols = categories or parameters).posterior_mean_pairwise: Symmetric matrix of posterior meanpairwise interaction strengths.posterior_mean_indicator: Symmetric matrix of posterior meaninclusion probabilities (if edge selection was enabled).Additional summaries returned when
edge_prior = "Stochastic-Block". For more details about this priorsee Sekulovski et al. (2025).posterior_summary_pairwise_allocations: Data frame withposterior summaries (mean, sd, MCSE, ESS, Rhat) for the pairwisecluster co-occurrence of the nodes. This serves to indicatewhether the estimated posterior allocations,co-clustering matrixand posterior cluster probabilities (see blow) have converged.posterior_coclustering_matrix: a symmetric matrix ofpairwise proportions of occurrence of every variable. This matrixcan be plotted to visually inspect the estimated number of clustersand visually inspect nodes that tend to switch clusters.posterior_mean_allocations: A vector with the posterior meanof the cluster allocations of the nodes. This is calculated using the methodproposed in Dahl (2009).posterior_mode_allocations: A vector with the posteriormode of the cluster allocations of the nodes.posterior_num_blocks: A data frame with the estimatedposterior inclusion probabilities for all the possible number of clusters.
raw_samples: A list of raw MCMC draws per chain:mainList of main effect samples.
pairwiseList of pairwise effect samples.
indicatorList of indicator samples(if edge selection enabled).
allocationsList of cluster allocations(if SBM prior used).
nchainsNumber of chains.
niterNumber of post–warmup iterations per chain.
parameter_namesNamed lists of parameter labels.
arguments: A list of function call arguments and metadata(e.g., number of variables, warmup, sampler settings, package version).
Thesummary() method prints formatted posterior summaries, andcoef() extracts posterior mean matrices.
NUTS diagnostics (tree depth, divergences, energy, E-BFMI) are includedinfit$nuts_diag ifupdate_method = "nuts".
Ordinal Variables
The function supports two types of ordinal variables:
Regular ordinal variables:Assigns a category threshold parameter to each response category except thelowest. The model imposes no additional constraints on the distribution ofcategory responses.
Blume-Capel ordinal variables:Assume a baseline category (e.g., a “neutral” response) and score responsesby distance from this baseline. Category thresholds are modeled as:
\mu_{c} = \alpha \cdot c + \beta \cdot (c - b)^2
where:
\mu_{c}: category threshold for categoryc\alpha: linear trend across categories\beta: preference toward or away from the baselineIf
\beta < 0, the model favors responses near the baselinecategory;if
\beta > 0, it favors responses farther away (i.e.,extremes).
b: baseline category
Edge Selection
Whenedge_selection = TRUE, the function performs Bayesian variableselection on the pairwise interactions (edges) in the MRF usingspike-and-slab priors.
Supported priors for edge inclusion:
Bernoulli: Fixed inclusion probability across edges.
Beta-Bernoulli: Inclusion probability is assigned a Betaprior distribution.
Stochastic-Block: Cluster-based edge priors with Beta,Dirichlet, and Poisson hyperpriors.
All priors operate via binary indicator variables controlling the inclusionor exclusion of each edge in the MRF.
Prior Distributions
Pairwise effects: Modeled with a Cauchy (slab) prior.
Main effects: Modeled using a beta-primedistribution.
Edge indicators: Use either a Bernoulli, Beta-Bernoulli, orStochastic-Block prior (as above).
Sampling Algorithms and Warmup
Parameters are updated within a Gibbs framework, but the conditionalupdates can be carried out using different algorithms:
Adaptive Metropolis–Hastings: Componentwise random–walkupdates for main effects and pairwise effects. Proposal standarddeviations are adapted during burn–in via Robbins–Monro updatestoward a target acceptance rate.
Hamiltonian Monte Carlo (HMC): Joint updates of allparameters using fixed–length leapfrog trajectories. Step size istuned during warmup via dual–averaging; the diagonal mass matrix canalso be adapted if
learn_mass_matrix = TRUE.No–U–Turn Sampler (NUTS): An adaptive extension of HMCthat dynamically chooses trajectory lengths. Warmup uses a stagedadaptation schedule (fast–slow–fast) to stabilize step size and, ifenabled, the mass matrix.
Whenedge_selection = TRUE, updates of edge–inclusion indicatorsare carried out with Metropolis–Hastings steps. These are switched onafter the core warmup phase, ensuring that graph updates occur only oncethe samplers’ tuning parameters (step size, mass matrix, proposal SDs)have stabilized.
After warmup, adaptation is disabled. Step size and mass matrix arefixed at their learned values, and proposal SDs remain constant.
Warmup and Adaptation
The warmup procedure inbgm is based on the multi–stage adaptationschedule used in Stan (Stan Development Team 2023). Warmup iterations aresplit into several phases:
Stage 1 (fast adaptation): A short initial intervalwhere only step size (for HMC/NUTS) is adapted, allowing the chainto move quickly toward the typical set.
Stage 2 (slow windows): A sequence of expanding,memoryless windows where both step size and, if
learn_mass_matrix = TRUE, the diagonal mass matrix areadapted. Each window ends with a reset of the dual–averaging schemefor improved stability.Stage 3a (final fast interval): A short interval at theend of the core warmup where the step size is adapted one final time.
Stage 3b (proposal–SD tuning): Only active when
edge_selection = TRUEunder HMC/NUTS. In this phase,Robbins–Monro adaptation of proposal standard deviations isperformed for the Metropolis steps used in edge–selection moves.Stage 3c (graph selection warmup): Also only relevantwhen
edge_selection = TRUE. At the start of this phase, arandom graph structure is initialized, and Metropolis–Hastingsupdates for edge inclusion indicators are switched on.
Whenedge_selection = FALSE, the total number of warmup iterationsequals the user–specifiedburnin. Whenedge_selection = TRUEandupdate_method is"nuts" or"hamiltonian-mc",the schedule automatically appends additional Stage-3b and Stage-3cintervals, so the total warmup is strictly greater than the requestedburnin.
After all warmup phases, the sampler transitions to the sampling phasewith adaptation disabled. Step size and mass matrix (for HMC/NUTS) arefixed at their learned values, and proposal SDs remain constant.
This staged design improves stability of proposals and ensures that bothlocal parameters (step size) and global parameters (mass matrix, proposalSDs) are tuned before collecting posterior samples.
For adaptive Metropolis–Hastings runs, step size and mass matrixadaptation are not relevant. Proposal SDs are tuned continuously duringburn–in using Robbins–Monro updates, without staged fast/slow intervals.
Missing Data
Ifna_action = "listwise", observations with missing values areremoved.Ifna_action = "impute", missing values are imputed during Gibbssampling.
References
Dahl DB (2009).“Modal clustering in a class of product partition models.”Bayesian Analysis,4(2), 243–264.doi:10.1214/09-BA409.
Marsman M, van den Bergh D, Haslbeck JMB (2025).“Bayesian analysis of the ordinal Markov random field.”Psychometrika,90, 146–-182.
Sekulovski N, Arena G, Haslbeck JMB, Huth KBS, Friel N, Marsman M (2025).“A Stochastic Block Prior for Clustering in Graphical Models.”Retrieved fromhttps://osf.io/preprints/psyarxiv/29p3m_v1.OSF preprint.
Stan Development Team (2023).Stan Modeling Language Users Guide and Reference Manual.Version 2.33,https://mc-stan.org/docs/.
See Also
vignette("intro", package = "bgms") for a worked example.
Examples
# Run bgm on subset of the Wenchuan datasetfit = bgm(x = Wenchuan[, 1:5])# Posterior inclusion probabilitiessummary(fit)$indicator# Posterior pairwise effectssummary(fit)$pairwiseBayesian Estimation and Variable Selection for Group Differences in Markov Random Fields
Description
ThebgmCompare function estimates group differences in categorythreshold parameters (main effects) and pairwise interactions (pairwiseeffects) of a Markov Random Field (MRF) for binary and ordinal variables.Groups can be defined either by supplying two separate datasets (x andy) or by a group membership vector. Optionally, Bayesian variableselection can be applied to identify differences across groups.
Usage
bgmCompare( x, y, group_indicator, difference_selection = TRUE, variable_type = "ordinal", baseline_category, difference_scale = 1, difference_prior = c("Bernoulli", "Beta-Bernoulli"), difference_probability = 0.5, beta_bernoulli_alpha = 1, beta_bernoulli_beta = 1, pairwise_scale = 2.5, main_alpha = 0.5, main_beta = 0.5, iter = 1000, warmup = 1000, na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis", "hamiltonian-mc"), target_accept, hmc_num_leapfrogs = 100, nuts_max_depth = 10, learn_mass_matrix = FALSE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, main_difference_model, reference_category, main_difference_scale, pairwise_difference_scale, pairwise_difference_prior, main_difference_prior, pairwise_difference_probability, main_difference_probability, pairwise_beta_bernoulli_alpha, pairwise_beta_bernoulli_beta, main_beta_bernoulli_alpha, main_beta_bernoulli_beta, interaction_scale, threshold_alpha, threshold_beta, burnin, save)Arguments
x | A data frame or matrix of binary and ordinal responses forGroup 1. Variables should be coded as nonnegative integers starting at0. For ordinal variables, unused categories are collapsed; forBlume–Capel variables, all categories are retained. |
y | Optional data frame or matrix for Group 2 (two-group designs).Must have the same variables (columns) as |
group_indicator | Optional integer vector of group memberships forrows of |
difference_selection | Logical. If |
variable_type | Character vector specifying type of each variable: |
baseline_category | Integer or vector giving the baseline categoryfor Blume–Capel variables. |
difference_scale | Double. Scale of the Cauchy prior for differenceparameters. Default: |
difference_prior | Character. Prior for difference inclusion: |
difference_probability | Numeric. Prior inclusion probability fordifferences (Bernoulli prior). Default: |
beta_bernoulli_alpha,beta_bernoulli_beta | Doubles. Shape parametersof the Beta prior for inclusion probabilities in the Beta–Bernoullimodel. Defaults: |
pairwise_scale | Double. Scale of the Cauchy prior for baselinepairwise interactions. Default: |
main_alpha,main_beta | Doubles. Shape parameters of the beta-primeprior for baseline threshold parameters. Defaults: |
iter | Integer. Number of post–warmup iterations per chain.Default: |
warmup | Integer. Number of warmup iterations before sampling.Default: |
na_action | Character. How to handle missing data: |
update_method | Character. Sampling algorithm: |
target_accept | Numeric between 0 and 1. Target acceptance rate.Defaults: 0.44 (Metropolis), 0.65 (HMC), 0.60 (NUTS). |
hmc_num_leapfrogs | Integer. Leapfrog steps for HMC. Default: |
nuts_max_depth | Integer. Maximum tree depth for NUTS. Default: |
learn_mass_matrix | Logical. If |
chains | Integer. Number of parallel chains. Default: |
cores | Integer. Number of CPU cores. Default: |
display_progress | Character. Controls progress reporting: |
seed | Optional integer. Random seed for reproducibility. |
main_difference_model,reference_category,pairwise_difference_scale,main_difference_scale,pairwise_difference_prior,main_difference_prior,pairwise_difference_probability,main_difference_probability,pairwise_beta_bernoulli_alpha,pairwise_beta_bernoulli_beta,main_beta_bernoulli_alpha,main_beta_bernoulli_beta,interaction_scale,threshold_alpha,threshold_beta,burnin,save | 'r lifecycle::badge("deprecated")'Deprecated arguments as of **bgms 0.1.6.0**.Use 'difference_scale', 'difference_prior', 'difference_probability','beta_bernoulli_alpha', 'beta_bernoulli_beta', 'baseline_category','pairwise_scale', and 'warmup' instead. |
Details
This function extends the ordinal MRF frameworkMarsman et al. (2025) to multiplegroups. The basic idea of modeling, analyzing, and testing groupdifferences in MRFs was introduced inMarsman et al. (2024), wheretwo–group comparisons were conducted using adaptive Metropolis sampling.The present implementation generalizes that approach to more than twogroups and supports additional samplers (HMC and NUTS) with staged warmupadaptation.
Key components of the model:
Value
A list of class"bgmCompare" containing posterior summaries,posterior mean matrices, and raw MCMC samples:
posterior_summary_main_baseline,posterior_summary_pairwise_baseline: summaries of baselinethresholds and pairwise interactions.posterior_summary_main_differences,posterior_summary_pairwise_differences: summaries of groupdifferences in thresholds and pairwise interactions.posterior_summary_indicator: summaries of inclusionindicators (ifdifference_selection = TRUE).posterior_mean_main_baseline,posterior_mean_pairwise_baseline: posterior mean matrices(legacy style).raw_samples: list of raw draws per chain for main,pairwise, and indicator parameters.arguments: list of function call arguments and metadata.
Thesummary() method prints formatted summaries, andcoef() extracts posterior means.
NUTS diagnostics (tree depth, divergences, energy, E-BFMI) are includedinfit$nuts_diag ifupdate_method = "nuts".
Pairwise Interactions
For variablesi andj, the group-specific interaction isrepresented as:
\theta_{ij}^{(g)} = \phi_{ij} + \delta_{ij}^{(g)},
where\phi_{ij} is the baseline effect and\delta_{ij}^{(g)} are group differences constrained to sum to zero.
Ordinal Variables
Regular ordinal variables: category thresholds are decomposed into abaseline plus group differences for each category.
Blume–Capel variables: category thresholds are quadratic in thecategory index, with both the linear and quadratic terms split into abaseline plus group differences.
Variable Selection
Whendifference_selection = TRUE, spike-and-slab priors areapplied to difference parameters:
Bernoulli: fixed prior inclusion probability.
Beta–Bernoulli: inclusion probability given a Beta prior.
Sampling Algorithms and Warmup
Parameters are updated within a Gibbs framework, using the samesampling algorithms and staged warmup scheme described inbgm:
Adaptive Metropolis–Hastings: componentwise random–walkproposals with Robbins–Monro adaptation of proposal SDs.
Hamiltonian Monte Carlo (HMC): joint updates with fixedleapfrog trajectories; step size and optionally the mass matrix areadapted during warmup.
No–U–Turn Sampler (NUTS): an adaptive HMC variant withdynamic trajectory lengths; warmup uses the same staged adaptationschedule as HMC.
For details on the staged adaptation schedule (fast–slow–fast phases),seebgm. In addition, whendifference_selection = TRUE, updates of inclusion indicators aredelayed until late warmup. In HMC/NUTS, this appends two extra phases(Stage-3b and Stage-3c), so that the total number of warmup iterationsexceeds the user-specifiedwarmup.
After warmup, adaptation is disabled: step size and mass matrix are fixedat their learned values, and proposal SDs remain constant.
References
Marsman M, Waldorp LJ, Sekulovski N, Haslbeck JMB (2024).“Bayes factor tests for group differences in ordinal and binary graphical models.”Retrieved from https://osf.io/preprints/osf/f4pk9.OSF preprint.
Marsman M, van den Bergh D, Haslbeck JMB (2025).“Bayesian analysis of the ordinal Markov random field.”Psychometrika,90, 146–-182.
See Also
vignette("comparison", package = "bgms") for a worked example.
Examples
## Not run: # Run bgmCompare on subset of the Boredom datasetx = Boredom[Boredom$language == "fr", 2:6]y = Boredom[Boredom$language != "fr", 2:6]fit <- bgmCompare(x, y)# Posterior inclusion probabilitiessummary(fit)$indicator# Bayesian model averaged main effects for the groupscoef(fit)$main_effects_groups# Bayesian model averaged pairwise effects for the groupscoef(fit)$pairwise_effects_groups## End(Not run)Extract Coefficients from a bgmCompare Object
Description
Returns posterior means for raw parameters (baseline + differences)and group-specific effects from abgmCompare fit, as well as inclusion indicators.
Usage
## S3 method for class 'bgmCompare'coef(object, ...)Arguments
object | An object of class |
... | Ignored. |
Value
A list with components:
- main_effects_raw
Posterior means of the raw main-effect parameters(variables x [baseline + differences]).
- pairwise_effects_raw
Posterior means of the raw pairwise-effect parameters(pairs x [baseline + differences]).
- main_effects_groups
Posterior means of group-specific main effects(variables x groups), computed as baseline plus projected differences.
- pairwise_effects_groups
Posterior means of group-specific pairwise effects(pairs x groups), computed as baseline plus projected differences.
- indicators
Posterior mean inclusion probabilities as a symmetric matrix,with diagonals corresponding to main effects and off-diagonals to pairwise effects.
Extract Coefficients from a bgms Object
Description
Returns the posterior mean thresholds, pairwise effects, and edge inclusion indicators from abgms model fit.
Usage
## S3 method for class 'bgms'coef(object, ...)Arguments
object | An object of class |
... | Ignored. |
Value
A list with the following components:
- main
Posterior mean of the category threshold parameters.
- pairwise
Posterior mean of the pairwise interaction matrix.
- indicator
Posterior mean of the edge inclusion indicators (if available).
Extractor Functions for bgms Objects
Description
Extractor Functions for bgms Objects
Usage
extract_arguments(bgms_object)## S3 method for class 'bgms'extract_arguments(bgms_object)## S3 method for class 'bgmCompare'extract_arguments(bgms_object)extract_indicators(bgms_object)## S3 method for class 'bgms'extract_indicators(bgms_object)## S3 method for class 'bgmCompare'extract_indicators(bgms_object)extract_posterior_inclusion_probabilities(bgms_object)## S3 method for class 'bgms'extract_posterior_inclusion_probabilities(bgms_object)extract_sbm(bgms_object)## S3 method for class 'bgms'extract_sbm(bgms_object)## S3 method for class 'bgmCompare'extract_posterior_inclusion_probabilities(bgms_object)extract_indicator_priors(bgms_object)## S3 method for class 'bgms'extract_indicator_priors(bgms_object)## S3 method for class 'bgmCompare'extract_indicator_priors(bgms_object)extract_pairwise_interactions(bgms_object)## S3 method for class 'bgms'extract_pairwise_interactions(bgms_object)## S3 method for class 'bgmCompare'extract_pairwise_interactions(bgms_object)extract_category_thresholds(bgms_object)## S3 method for class 'bgms'extract_category_thresholds(bgms_object)## S3 method for class 'bgmCompare'extract_category_thresholds(bgms_object)extract_group_params(bgms_object)## S3 method for class 'bgmCompare'extract_group_params(bgms_object)extract_edge_indicators(bgms_object)extract_pairwise_thresholds(bgms_object)Details
These functions extract various components from objects returned by the 'bgm()' function,such as edge indicators, posterior inclusion probabilities, and parameter summaries.
Internally, indicator samples were stored in '$gamma' (pre-0.1.4) and'$indicator' (0.1.4–0.1.5). As of **bgms 0.1.6.0**, they are stored in'$raw_samples$indicators'. Access via older names is supported but deprecated.
Posterior inclusion probabilities are computed from edge indicators.
Internally, indicator samples were stored in '$gamma' (pre-0.1.4) and'$indicator' (0.1.4–0.1.5). As of **bgms 0.1.6.0**, they are stored in'$raw_samples$indicator'. Access via older names is supported but deprecated.
Category thresholds were previously stored in '$main_effects' (pre-0.1.4) and'$posterior_mean_main' (0.1.4–0.1.5). As of **bgms 0.1.6.0**, they are storedin '$posterior_summary_main'. Access via older names is supported but deprecated.
Functions
- 'extract_arguments()' – Extract model arguments- 'extract_indicators()' – Get sampled edge indicators- 'extract_posterior_inclusion_probabilities()' – Posterior edge inclusion probabilities- 'extract_pairwise_interactions()' – Posterior mean of pairwise interactions- 'extract_category_thresholds()' – Posterior mean of category thresholds- 'extract_indicator_priors()' – Prior structure used for edge indicators- 'extract_sbm' – Extract stochastic block model parameters (if applicable)
Sample observations from the ordinal MRF
Description
This function samples states from the ordinal MRF using a Gibbs sampler. TheGibbs sampler is initiated with random values from the response options,after which it proceeds by simulating states for each variable from a logisticmodel using the other variable states as predictor variables.
Usage
mrfSampler( no_states, no_variables, no_categories, interactions, thresholds, variable_type = "ordinal", reference_category, iter = 1000)Arguments
no_states | The number of states of the ordinal MRF to be generated. |
no_variables | The number of variables in the ordinal MRF. |
no_categories | Either a positive integer or a vector of positiveintegers of length |
interactions | A symmetric |
thresholds | A |
variable_type | What kind of variables are simulated? Can be a singlecharacter string specifying the variable type of all |
reference_category | An integer vector of length |
iter | The number of iterations used by the Gibbs sampler.The function provides the last state of the Gibbs sampler as output. Bydefault set to |
Details
There are two modeling options for the category thresholds. The defaultoption assumes that the category thresholds are free, except that the firstthreshold is set to zero for identification. The user then only needs tospecify the thresholds for the remaining response categories. This option isuseful for any type of ordinal variable and gives the user the most freedomin specifying their model.
The Blume-Capel option is specifically designed for ordinal variables thathave a special type of reference_category category, such as the neutralcategory in a Likert scale. The Blume-Capel model specifies the followingquadratic model for the threshold parameters:
\mu_{\text{c}} = \alpha \times \text{c} + \beta \times (\text{c} - \text{r})^2,
where\mu_{\text{c}} is the threshold for category c(which now includes zero),\alpha offers a linear trendacross categories (increasing threshold values if\alpha > 0 and decreasing threshold values if\alpha <0), if\beta < 0, it offers anincreasing penalty for responding in a category further away from thereference_category category r, while\beta > 0 suggests apreference for responding in the reference_category category.
Value
Ano_states byno_variables matrix of simulated states ofthe ordinal MRF.
Examples
# Generate responses from a network of five binary and ordinal variables.no_variables = 5no_categories = sample(1:5, size = no_variables, replace = TRUE)Interactions = matrix(0, nrow = no_variables, ncol = no_variables)Interactions[2, 1] = Interactions[4, 1] = Interactions[3, 2] = Interactions[5, 2] = Interactions[5, 4] = .25Interactions = Interactions + t(Interactions)Thresholds = matrix(0, nrow = no_variables, ncol = max(no_categories))x = mrfSampler(no_states = 1e3, no_variables = no_variables, no_categories = no_categories, interactions = Interactions, thresholds = Thresholds)# Generate responses from a network of 2 ordinal and 3 Blume-Capel variables.no_variables = 5no_categories = 4Interactions = matrix(0, nrow = no_variables, ncol = no_variables)Interactions[2, 1] = Interactions[4, 1] = Interactions[3, 2] = Interactions[5, 2] = Interactions[5, 4] = .25Interactions = Interactions + t(Interactions)Thresholds = matrix(NA, no_variables, no_categories)Thresholds[, 1] = -1Thresholds[, 2] = -1Thresholds[3, ] = sort(-abs(rnorm(4)), decreasing = TRUE)Thresholds[5, ] = sort(-abs(rnorm(4)), decreasing = TRUE)x = mrfSampler(no_states = 1e3, no_variables = no_variables, no_categories = no_categories, interactions = Interactions, thresholds = Thresholds, variable_type = c("b","b","o","b","o"), reference_category = 2)Print method for 'bgmCompare' objects
Description
Minimal console output for 'bgmCompare' fit objects.
Usage
## S3 method for class 'bgmCompare'print(x, ...)Arguments
x | An object of class 'bgmCompare'. |
... | Ignored. |
Print method for 'bgms' objects
Description
Minimal console output for 'bgms' fit objects.
Usage
## S3 method for class 'bgms'print(x, ...)Arguments
x | An object of class 'bgms'. |
... | Ignored. |
Summary method for 'bgmCompare' objects
Description
Returns posterior summaries and diagnostics for a fitted 'bgmCompare' model.
Usage
## S3 method for class 'bgmCompare'summary(object, ...)Arguments
object | An object of class 'bgmCompare'. |
... | Currently ignored. |
Value
An object of class 'summary.bgmCompare' with posterior summaries.
Summary method for 'bgms' objects
Description
Returns posterior summaries and diagnostics for a fitted 'bgms' model.
Usage
## S3 method for class 'bgms'summary(object, ...)Arguments
object | An object of class 'bgms'. |
... | Currently ignored. |
Value
An object of class 'summary.bgms' with posterior summaries.