Package {babebi}


Type: Package
Title: Bayesian Estimation and Validation for Small-N Designs with Rater Bias
Version: 1.0.0
Description: Analyses complete two-time, two-rater repeated-measures designs. The original workflow uses a normal approximation to the posterior of a change-score regression with plug-in residual variance, a Bayesian information criterion (BIC) approximation to a Bayes factor, and a simplified Monte Carlo simulation. The extended workflow provides bivariate Gaussian change-score models with four covariance structures, exact conjugate posterior distributions under model-specific reference or proper priors, and posterior and predictive contrasts. Proper priors enable marginal likelihoods, Bayes factors and prior sensitivity analyses. Agreement analysis distinguishes mean discrepancies from individual predictive agreement. The package includes comparative simulation studies, empirical plug-in scenarios, Monte Carlo standard errors and simulation-based calibration. A hierarchical cumulative probit model supports ordinal outcomes using Gibbs sampling and convergence diagnostics. The original methods remain available for reproduction of Gianeselli, Bosco and Basso (2026) <doi:10.1177/01466216261465754>. See Morris, White and Crowther (2019) <doi:10.1002/sim.8086> for simulation design and Albert and Chib (1993) <doi:10.1080/01621459.1993.10476321> for latent Gaussian augmentation.
License: GPL-3
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: stats, graphics
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown
Config/testthat/edition: 3
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
VignetteBuilder: knitr
Packaged: 2026-12-01 11:57:05 UTC; irene
Author: Irene Gianeselli ORCID iD [aut, cre] (affiliation: Free University of Bozen-Bolzano), Andrea Bosco ORCID iD [aut] (affiliation: University of Bari Aldo Moro), Demis Basso ORCID iD [aut] (affiliation: Free University of Bozen-Bolzano)
Maintainer: Irene Gianeselli <irene.gianeselli@unibz.it>
Repository: CRAN
Date/Publication: 2026-12-01 23:20:49 UTC

Assess Bayesian agreement between paired change scores

Description

Assesses agreement between the changes recorded by two raters in a Gaussian bivariate pre-post model.

Usage

agreement_bivariate(
  posterior,
  margin = NULL,
  min_coverage = NULL,
  content = 0.95,
  level = 0.95,
  n_draws = 10000L,
  seed = NULL,
  keep_draws = FALSE,
  rel_tol = 1e-08,
  abs_tol = 1e-10,
  subdivisions = 1000L
)

Arguments

posterior

An object of class babebi_posterior returned by posterior_bivariate().

margin

Optional strictly positive finite scalar defining the maximum practically acceptable absolute discrepancy between the two raters' change scores. If NULL, practical agreement probabilities are not calculated.

min_coverage

Optional scalar strictly between 0 and 1 defining the minimum acceptable population probability of an individual discrepancy within the specified margin. Requires a non-NULL margin.

content

Probability content of the population limits of agreement and the posterior predictive interval. Must lie strictly between 0 and 1. Default is 0.95.

level

Probability content of the marginal posterior credible intervals for population parameters. Must lie strictly between 0 and 1. Default is 0.95.

n_draws

Number of independent posterior draws used to summarise the nonlinear agreement quantities. An integer of at least 1000. Default is 10000.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

keep_draws

Logical scalar indicating whether the posterior draws should be retained in the returned object. Default is FALSE.

rel_tol

Relative integration tolerance passed to contrast_bivariate().

abs_tol

Absolute integration tolerance passed to contrast_bivariate().

subdivisions

Maximum number of integration subdivisions passed to contrast_bivariate().

Details

The analysis distinguishes systematic between-rater discrepancy, individual disagreement, population limits of agreement, posterior predictive intervals, and practical agreement.

Agreement is assessed on the scale of observed change scores. The individual discrepancy is defined as the second-rater change minus the reference-rater change.

Its population mean is gamma, and its population variance is the sum of the two rater-specific change-score variances minus twice their covariance.

The population variance of individual discrepancies follows an inverse-gamma posterior under models M0, M2, and M3. Under M1, it is distributed as the sum of two independent inverse-gamma variables.

The conditional posterior of gamma, given the discrepancy variance, is Gaussian with variance equal to the discrepancy variance divided by the posterior precision multiplier kappa.

Population limits of agreement are the conditional Gaussian quantiles of the individual discrepancy distribution. Their posterior uncertainty is evaluated through independent draws from the joint posterior of gamma and the discrepancy variance.

The descriptive limits are calculated using the sample mean and sample standard deviation of the observed discrepancies. These are descriptive estimates, not confidence intervals.

The posterior predictive interval concerns the discrepancy of a new independent subject. Its probability content is evaluated after integrating over parameter uncertainty using contrast_bivariate().

The marginal credible intervals for the two population limits do not constitute a joint credible region for those limits. The interval formed by the posterior medians of the population limits does not necessarily have the nominal posterior predictive probability content.

When a practical margin is supplied, the function reports:

The posterior expectation of the conditional probability of practical agreement equals the posterior predictive probability of practical agreement.

The former is also estimated from the independent posterior draws and reported with its Monte Carlo standard error.

Monte Carlo standard errors for event probabilities are estimated using the Bernoulli variance. An estimated standard error of zero when all sampled events have the same outcome does not establish that the underlying probability is exactly zero or one.

Analytical marginal quantiles are used for the population discrepancy variance and its standard deviation under models M0, M2, and M3. Under M1, these quantiles are estimated by independent posterior sampling.

The posterior expectation of the discrepancy variance is reported only when it is finite. Posterior medians and credible intervals remain available when this expectation is not finite.

The Bland-Altman representation uses individual differences against the arithmetic mean of the two change scores. Its descriptive regression slope does not establish a causal proportional-bias mechanism.

Agreement of observed changes is not equivalent to reliability or validity of an underlying latent change construct. The analysis does not separately identify true change and measurement-error components.

Value

A named list of class babebi_agreement containing:

model, N, prior_type

Model structure, number of subjects, and prior strategy.

rater_levels

Original rater ordering.

content, level

Population and predictive interval content, and posterior credible interval content.

n_draws, seed

Posterior sampling settings.

margin, min_coverage

Practical agreement settings.

observed

Data frame of individual changes, their arithmetic means, and their discrepancies.

descriptive

Sample mean, variance, standard deviation, descriptive limits of agreement, descriptive regression slope, and observed proportion within the practical margin when supplied.

bias

Posterior discrepancy contrast returned by contrast_bivariate().

predictive

Predictive discrepancy contrast returned by contrast_bivariate().

variance_distribution

Posterior distributional specification of the discrepancy variance.

expected_variance

Posterior expectation of the population discrepancy variance, when finite.

expected_variance_exists

Logical indicator of a finite posterior expectation of the discrepancy variance.

parameters

Data frame of posterior medians and equal-tailed credible intervals for the discrepancy mean, variance, standard deviation, population limits of agreement, and conditional practical coverage when applicable. The calculation method is identified.

practical

Practical agreement probabilities and Monte Carlo standard errors, or NULL if no margin was supplied.

draws

Posterior draws when keep_draws = TRUE, otherwise NULL.

References

Alari, K. M., Kim, S. B., & Wand, J. O. (2021). A tutorial of Bland Altman analysis in a Bayesian framework. Measurement in Physical Education and Exercise Science, 25(2), 137-148. doi:10.1080/1091367X.2020.1853130

Bland, J. M., & Altman, D. G. (1986). Statistical methods for assessing agreement between two methods of clinical measurement. The Lancet, 327(8476), 307-310. doi:10.1016/S0140-6736(86)90837-8

Bland, J. M., & Altman, D. G. (1999). Measuring agreement in method comparison studies. Statistical Methods in Medical Research, 8(2), 135-160. doi:10.1177/096228029900800204

See Also

posterior_bivariate(), contrast_bivariate(), draw_agreement, plot.babebi_agreement

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), 4),
  rater = rep(c("r1", "r2"), 8),
  y = c(0, 0, 1, 2,
        0, 0, 2, 4,
        0, 0, 3, 1,
        0, 0, 4, 5)
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

prior <- bivariate_prior(
  location = c(0, 0),
  kappa = 2,
  shape = 3,
  covariance = diag(c(2, 2))
)

post <- posterior_bivariate(fit, prior)

agreement <- agreement_bivariate(
  post,
  margin = 0.5,
  min_coverage = 0.8,
  n_draws = 2000,
  seed = 123
)

print(agreement)
plot(agreement)


Run the babebi workflow on user-supplied data

Description

Fits the babebi model to observed data and, optionally, performs Monte Carlo validation calibrated on the observed design.

Usage

babebi(
  data,
  id,
  time,
  rater,
  outcome,
  time_order = NULL,
  rater_order = NULL,
  validate = TRUE,
  R = 1000,
  N = NULL,
  delta = NULL,
  bias_r2 = NULL,
  n_draws = 4000,
  seed = NULL
)

Arguments

data

A data frame in long format.

id

Unquoted column name identifying subjects or a character string.

time

Unquoted column name identifying time points or a character string.

rater

Unquoted column name identifying raters or a character string.

outcome

Unquoted column name containing the observed score or a character string.

time_order

Optional character vector of length 2 giving the order of the time factor: baseline first, follow-up second.

rater_order

Optional character vector of length 2 giving the order of the rater factor: reference rater first, second rater second.

validate

Logical; if TRUE, run Monte Carlo validation after model fitting.

R

Number of Monte Carlo repetitions when validate = TRUE.

N

Optional override for the sample size used in validation.

delta

Optional override for the pre-post effect used in validation.

bias_r2

Optional override for the additive bias of the second rater used in validation.

n_draws

Number of posterior draws used in model fitting.

seed

Optional integer seed for reproducibility.

Details

This is the historical basic workflow. The normal posterior approximation and BIC evidence require caution in small samples, and the original Monte Carlo routine does not reproduce within-subject dependence or observed variances. See the choosing-a-workflow and advanced-workflow vignettes for alternatives.

Before fitting, check that outcomes and change scores are finite. For zero or near-zero residual variance and the scale-dependent numerical safeguards of the historical workflow, see fit_model.

Value

A named list containing:

fit

A babebi_fit object returned by fit_model().

validation

A babebi_validation object returned by montecarlo_from_data() when validate = TRUE, otherwise NULL.

call

The original function call.

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    3.0, 3.2, 3.8, 4.0,
    2.9, 3.1, 3.5, 3.7,
    3.4, 3.6, 4.0, 4.1,
    3.1, 3.3, 3.9, 4.0
  )
)

res <- babebi(
  data = dat,
  id = id,
  time = time,
  rater = rater,
  outcome = y,
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2"),
  validate = TRUE,
  R = 100,
  n_draws = 500,
  seed = 123
)

print(res$fit)
summary(res$fit)
plot(res$fit)
print(res$validation)


Compute Bayes factors for hypotheses about bivariate contrasts

Description

Computes Bayes factors for point, directional, and interval hypotheses concerning linear contrasts of the population mean parameters of a Gaussian bivariate change-score model.

Usage

bayesfactor_bivariate(
  posterior,
  contrast,
  weight = NULL,
  hypothesis = "point",
  null = NULL,
  bounds = NULL,
  rel_tol = 1e-08,
  subdivisions = 1000L
)

Arguments

posterior

An object of class babebi_posterior obtained under a proper conjugate prior.

contrast

A predefined contrast name or a numeric vector of coefficients for beta and gamma, as specified in contrast_bivariate().

weight

Optional weight for the second rater when contrast = "weighted".

hypothesis

Character string specifying the hypothesis comparison: "point", "greater", "less", or "interval". Default is "point".

null

Finite numeric scalar defining the point null or directional boundary. When NULL, zero is used for point and directional hypotheses. Must be NULL for interval hypotheses.

bounds

Numeric vector of two finite, strictly increasing bounds defining the interval hypothesis. Required for hypothesis = "interval" and otherwise NULL.

rel_tol

Relative numerical integration tolerance between 1e-10 and 1e-4. Default is 1e-8.

subdivisions

Maximum number of subdivisions per adaptive integration interval. An integer of at least 100. Default is 1000.

Details

Inference is based on proper conjugate priors and analytical posterior distributions returned by posterior_bivariate().

The supported hypothesis comparisons are:

point

The unrestricted continuous alternative H1 against the point null H0, where the contrast equals null.

greater

H1 states that the contrast is greater than null; H0 is its complement.

less

H1 states that the contrast is less than null; H0 is its complement.

interval

H1 states that the contrast lies strictly between bounds; H0 is the complementary region.

For point hypotheses, the prior distribution of the nuisance parameters under H0 is defined as the conditional prior induced by the unrestricted model at the null contrast value.

Under this specification, the Savage-Dickey density ratio gives BF01 as the posterior density divided by the prior density at the null value. BF10 is its reciprocal.

The calculation does not apply to arbitrary alternative specifications of the nuisance-parameter prior under H0.

For directional and interval hypotheses, the two model-specific priors are obtained by restricting and normalising the proper encompassing prior on their respective regions.

BF10 is the ratio of the posterior odds to the prior odds of the region defining H1 under the encompassing model.

Prior and posterior probabilities for constrained hypotheses refer to regions under the encompassing model. They are not automatically posterior model probabilities for separately assigned hypothesis weights.

Under models M0 and M3, marginal contrast densities and probabilities are evaluated using univariate Student distributions. The same approach applies to single-component contrasts under models M1 and M2.

General two-component contrasts under M1 and M2 are evaluated using a beta mixture of Student distributions. If the component degrees of freedom are nu, the conditional Student distribution has 2 * nu degrees of freedom and its variance scale depends on a Beta(nu / 2, nu / 2) mixing variable.

Numerical mixture integration uses a logit transformation of the beta mixing variable, scale-dependent interval partitioning, logarithmic rescaling, adaptive quadrature, and an aggregate error check.

Numerical error estimates are not rigorous bounds. Extreme tail regions or poorly resolved interval probabilities may be rejected when the requested numerical accuracy cannot be established.

Bayes factors are calculated on the logarithmic scale. Ordinary-scale values may be infinite or zero because of floating-point limitations.

Only hypotheses about population parameters are supported. Predictive contrasts concern future observations and are not treated as competing parameter hypotheses by this function.

Improper reference priors are not supported.

No random-number generation is used.

Value

A named list containing:

model

Covariance structure.

contrast

Contrast name.

coefficients

Coefficients for beta and gamma.

hypothesis

Type of hypothesis comparison.

null

Null value or directional boundary, if applicable.

bounds

Interval bounds, if applicable.

H1, H0

Descriptions of the competing hypotheses.

prior_method, posterior_method

Marginal distribution evaluation methods.

prior_log_density, posterior_log_density

Log densities at the point null, or NA_real_ for regional hypotheses.

prior_probability, posterior_probability

Probability content of H1 under the encompassing prior and posterior, or NA_real_ for point hypotheses.

log_prior_probability, log_posterior_probability

Log probabilities of the H1 region.

log_prior_complement, log_posterior_complement

Log probabilities of the complementary region.

log_bf10, log_bf01

Natural logarithms of the Bayes factors.

bf10, bf01

Bayes factors on the ordinary scale.

rel_tol, subdivisions

Numerical integration settings.

References

Heck, D. W. (2019). A caveat on the Savage-Dickey density ratio: The case of computing Bayes factors for regression parameters. British Journal of Mathematical and Statistical Psychology, 72(2), 316-333. doi:10.1111/bmsp.12150

Klugkist, I., Kato, B., & Hoijtink, H. (2005). Bayesian model selection using encompassing priors. Statistica Neerlandica, 59(1), 57-69. doi:10.1111/j.1467-9574.2005.00279.x

Verdinelli, I., & Wasserman, L. (1995). Computing Bayes factors using a generalization of the Savage-Dickey density ratio. Journal of the American Statistical Association, 90(430), 614-618. doi:10.1080/01621459.1995.10476554

See Also

contrast_bivariate(), log_marginal_bivariate, sensitivity_bivariate

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), 4),
  rater = rep(c("r1", "r2"), 8),
  y = c(0, 0, 1, 2,
        0, 0, 2, 4,
        0, 0, 3, 1,
        0, 0, 4, 5)
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M1",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

prior <- bivariate_prior(
  c(0, 0), kappa = 2, shape = 3,
  covariance = diag(c(2, 2))
)

post <- posterior_bivariate(fit, prior)

point <- bayesfactor_bivariate(
  post, "discrepancy",
  hypothesis = "point",
  null = 0
)

point$bf10

equivalence <- bayesfactor_bivariate(
  post, "discrepancy",
  hypothesis = "interval",
  bounds = c(-0.2, 0.2)
)

equivalence$bf10


Specify a proper conjugate prior for a bivariate change-score model

Description

Constructs a proper conjugate prior for Bayesian inference under one of the Gaussian covariance structures available in fit_bivariate().

Usage

bivariate_prior(location, kappa, shape, covariance)

Arguments

location

Numeric vector of length 2 specifying the prior expected mean changes of the reference and second raters, respectively.

kappa

Positive finite scalar controlling the relative precision of the conditional prior distribution of the mean.

shape

Finite scalar greater than 1 controlling the prior distribution of the covariance parameters.

covariance

Symmetric positive-definite 2 by 2 numeric matrix specifying the prior expected covariance matrix of the paired change scores. Its rows and columns must follow the reference-rater and second-rater ordering.

Details

The prior is parametrised through the expected rater-specific mean changes, the relative precision of the prior mean, a shape parameter, and the expected covariance matrix of the paired change scores.

Conditional on the covariance matrix, the prior distribution of the mean vector is bivariate normal with mean location and covariance equal to the covariance matrix divided by kappa.

For models M0, M1, and M2, independent inverse-gamma priors are assigned to the free variance parameters in the appropriate orthonormal basis. Model M0 contains a single common variance.

The inverse-gamma distribution is parametrised by shape a and scale b, with density proportional to v^{-(a+1)} \exp(-b/v).

For each free variance parameter with prior expectation v_0, the inverse-gamma scale is b_0 = (a_0 - 1)v_0.

For model M3, an inverse-Wishart prior is assigned to the unrestricted covariance matrix. Its degrees of freedom are 2a_0 + 1, and its scale matrix is 2(a_0 - 1)\Sigma_0, where \Sigma_0 denotes covariance.

Under all four models, covariance represents the prior expected covariance matrix.

The covariance matrix must respect the restrictions of the fitted model. Compatibility with these restrictions is checked by posterior_bivariate().

These priors are conjugate and permit analytical posterior updating. They may introduce substantial prior information. The hyperparameters should be selected in relation to the measurement scale and substantive knowledge.

No universal default prior is supplied.

Value

A named list of class babebi_prior containing:

location

Prior expected rater-specific mean changes.

kappa

Relative prior precision of the mean vector.

shape

Prior shape parameter.

covariance

Prior expected covariance matrix.

References

Murphy, K. P. (2007). Conjugate Bayesian analysis of the Gaussian distribution. Technical report.

See Also

posterior_bivariate(), fit_bivariate()

Examples

prior <- bivariate_prior(
  location = c(0, 0),
  kappa = 1,
  shape = 3,
  covariance = diag(c(1, 1))
)

prior


Define a bivariate change-score simulation scenario

Description

Defines a theoretical data-generating mechanism for paired change scores from two raters, with optional systematic, magnitude-dependent, and stochastic perturbations.

Usage

bivariate_scenario(
  N,
  beta,
  gamma,
  covariance,
  distribution = "normal",
  df = NULL,
  shift = 0,
  slope = 0,
  noise_sd = 0
)

Arguments

N

Integer number of subjects, at least two.

beta

Finite population mean change for the reference rater.

gamma

Finite population mean discrepancy between the second and reference raters before perturbation.

covariance

Symmetric positive-definite 2 by 2 population covariance matrix of the unperturbed change scores.

distribution

Character string, either "normal" or "student". Default is "normal".

df

Degrees of freedom for the multivariate Student distribution. Must be finite and greater than two when distribution = "student", and NULL otherwise.

shift

Finite additive perturbation of the second-rater change score. Default is zero.

slope

Finite coefficient multiplying the centred reference-rater change in the perturbation of the second-rater change. Default is zero.

noise_sd

Non-negative finite standard deviation of an additional stochastic perturbation. Default is zero.

Details

Before perturbation, the population mean vector is (beta, beta + gamma).

Under the Gaussian mechanism, the second-rater change is modified by adding shift, the product of slope and the centred reference-rater change, and an independent centred Gaussian perturbation with standard deviation noise_sd.

The reference-rater change is not modified.

Under the Student mechanism, the Gaussian components and stochastic perturbation share the same independent subject-level radial scale factor. This preserves the multivariate Student family after perturbation.

In this parameterisation, covariance denotes the actual population covariance matrix under both distributional families, not the Student scale matrix.

The effective Student scale matrix is the effective covariance matrix multiplied by (df - 2) / df.

The effective mean discrepancy is gamma + shift. The slope and stochastic perturbation affect the covariance structure but do not modify the population mean discrepancy.

Simulation is performed directly from the effective mean vector and covariance matrix.

No implicit jitter or regularisation is applied.

Value

A named list of class babebi_scenario containing:

N

Number of subjects.

distribution, df

Generative distributional family and Student degrees of freedom, when applicable.

base_location, base_covariance

Population mean and covariance before perturbation.

location, covariance

Effective population mean and covariance after perturbation.

theta

Effective beta and gamma parameters.

perturbation

Specified perturbation parameters.

origin, calibration

Scenario provenance and empirical calibration information, when applicable.

See Also

scenario_from_fit, scenario_truth, simulate_bivariate

Examples

scenario <- bivariate_scenario(
  N = 8, beta = 0.5, gamma = 0.2,
  covariance = matrix(c(1, 0.4, 0.4, 2), 2),
  shift = 0.3, slope = 0.5, noise_sd = 0.2
)

scenario$theta
scenario$covariance


Compare Gaussian bivariate covariance models

Description

Compares the marginal likelihoods of two or more distinct Gaussian covariance structures fitted to the same paired change scores.

Usage

compare_bivariate(posteriors, reference, model_prior = NULL)

Arguments

posteriors

List containing at least two objects of class babebi_posterior, each representing a distinct covariance structure under a proper conjugate prior.

reference

Character string identifying the reference covariance structure among the supplied models.

model_prior

Optional named numeric vector of strictly positive finite prior model weights. Names must match the supplied covariance structures. Weights are normalised internally. If NULL, posterior model probabilities are not calculated.

Details

Bayes factors are reported relative to an explicitly specified reference model. Optional prior model weights are used to calculate posterior model probabilities.

Each posterior must have been obtained using the same observed paired change scores, subject ordering, time ordering, and rater ordering.

The input models must differ in their covariance structures. Alternative prior specifications within a single covariance structure can be examined using sensitivity_bivariate.

The log Bayes factor for each model is its log marginal likelihood minus that of the reference model.

When prior model weights are supplied, posterior model probabilities are calculated by normalising the product of the prior weights and marginal likelihoods.

The calculation is performed on the logarithmic scale using a log-sum-exp normalisation.

Proper priors need not be identical across models, but the resulting comparison depends on their substantive specification. Equal prior expected covariance matrices do not imply equivalent prior distributions across covariance structures.

No prior model probabilities are assumed by default.

Extremely large or small Bayes factors may be represented by Inf or zero on the ordinary scale. The finite log Bayes factors remain the primary numerical results.

Value

A data frame with one row per supplied model and the following columns:

model

Covariance structure.

reference

Logical indicator of the reference model.

log_marginal

Log marginal likelihood.

log_bf

Log Bayes factor relative to the reference.

bf

Bayes factor relative to the reference.

prior_probability

Normalised prior model probability, or NA_real_ if no weights were supplied.

posterior_probability

Posterior model probability, or NA_real_ if no weights were supplied.

References

Kass, R. E., & Raftery, A. E. (1995). Bayes factors. Journal of the American Statistical Association, 90(430), 773-795. doi:10.1080/01621459.1995.10476572

See Also

log_marginal_bivariate, sensitivity_bivariate

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), 4),
  rater = rep(c("r1", "r2"), 8),
  y = c(0, 0, 1, 2,
        0, 0, 2, 4,
        0, 0, 3, 1,
        0, 0, 4, 5)
)

prior <- bivariate_prior(
  c(0, 0), kappa = 2, shape = 3,
  covariance = diag(c(2, 2))
)

models <- c("M0", "M1", "M2", "M3")

posts <- lapply(models, function(m) {
  fit <- fit_bivariate(
    dat, id, time, rater, y,
    model = m,
    time_order = c("pre", "post"),
    rater_order = c("r1", "r2")
  )
  posterior_bivariate(fit, prior)
})

compare_bivariate(
  posts,
  reference = "M0",
  model_prior = c(M0 = 1, M1 = 1, M2 = 1, M3 = 1)
)


Compare simulation performance using paired repetitions

Description

Compares two analysis methods using their performance contributions from the same simulated datasets.

Usage

compare_validation(object, method_a, method_b, metric)

Arguments

object

An object of class babebi_simulation returned by validate_bivariate.

method_a

Name of the first analysis method.

method_b

Name of the second analysis method.

metric

Character vector identifying one or more repetition-level performance measures available from summarise_validation.

Details

Only repetitions with available performance contributions from both methods are used.

For each usable repetition, the contribution of method B is subtracted from the contribution of method A.

The estimated difference is the mean of these paired differences. Its Monte Carlo standard error is the sample standard deviation of the paired differences divided by the square root of the number of usable pairs.

The comparison accounts for the dependence induced by analysing the same simulated datasets.

A negative difference is favourable to method A for loss measures such as mean squared error or Brier score. The interpretation of signed errors and coverage differences depends on the intended performance criterion.

The comparison of mse concerns differences in mean squared error. Root mean squared error and empirical standard deviation are not repetition-level additive quantities and are not supported by this function.

The comparison is conditional on the availability of both methods for the selected performance measure. Failure-rate comparisons can separately quantify differences in computational availability.

Bayes factors from different evidence definitions, including BIC approximations and proper-prior comparisons, require substantive interpretation before their differences can be considered meaningful.

Value

A data frame containing the method names, performance measure, mean contributions of both methods on their common repetitions, paired difference, Monte Carlo standard error, number of usable pairs, and total number of repetitions.

See Also

validate_bivariate, summarise_validation


Estimate posterior and predictive contrasts of change scores

Description

Computes marginal distributions and inferential summaries for linear contrasts of the mean parameters of a Gaussian bivariate change-score model.

Usage

contrast_bivariate(
  posterior,
  contrast,
  weight = NULL,
  target = "posterior",
  level = 0.95,
  threshold = NULL,
  rope = NULL,
  rel_tol = 1e-08,
  abs_tol = 1e-10,
  subdivisions = 1000L
)

Arguments

posterior

An object of class babebi_posterior returned by posterior_bivariate().

contrast

Character string specifying a predefined contrast: "reference", "second", "average", "discrepancy", or "weighted". Alternatively, a finite numeric vector of length 2 specifying coefficients for beta and gamma. A named coefficient vector must contain the names beta and gamma.

weight

Numeric scalar between 0 and 1 specifying the contribution of the second rater to the weighted mean change. Required for contrast = "weighted" and otherwise NULL.

target

Character string specifying the inferential target. Either "posterior" for a population parameter or "predictive" for the corresponding contrast of a new subject's change scores.

level

Probability content of the equal-tailed interval. Must lie strictly between 0 and 1. Default is 0.95.

threshold

Optional non-negative finite scalar specifying a practically relevant magnitude on the contrast scale.

rope

Optional finite numeric vector of length 2 specifying the lower and upper bounds of a region of practical equivalence. The lower bound must be strictly smaller than the upper bound.

rel_tol

Relative tolerance for numerical integration. Must lie between 1e-12 and 1e-3. Default is 1e-8.

abs_tol

Absolute tolerance for numerical integration. Must lie between 1e-14 and 1e-3. Default is 1e-10.

subdivisions

Maximum number of subdivisions used for adaptive numerical integration. An integer of at least 100. Default is 1000.

Details

Contrasts may describe reference-rater change, second-rater change, average change, weighted change, systematic between-rater discrepancy, or a user-defined linear combination of the mean parameters.

Inference is based on the analytical posterior distributions returned by posterior_bivariate(). Student distributions are evaluated analytically. When a contrast involves two independent Student components, numerical convolution is used where necessary.

The mean parameters follow the reference-rater parametrisation: beta is the reference-rater mean change, and gamma is the second-rater mean change minus the reference-rater mean change.

The predefined contrasts are:

reference

Beta.

second

Beta + gamma.

average

Beta + gamma / 2.

discrepancy

Gamma.

weighted

Beta + weight * gamma.

User-defined contrasts take the form c_1\beta + c_2\gamma. At least one coefficient must be non-zero.

For a predictive target, the same linear transformation is applied to the paired change scores of a new independent subject from the same population.

Under models M0 and M3, each non-degenerate linear contrast follows a univariate Student distribution.

Under models M1 and M2, the marginal distribution of a contrast may involve a weighted sum of two independent Student variates. A single non-zero component is evaluated analytically. When both components have one degree of freedom, their sum is evaluated using the stability property of the Cauchy distribution.

All remaining two-component contrasts are evaluated by deterministic numerical convolution. The calculation uses symmetry, standardisation, and direct evaluation of tail probabilities. Quantiles are obtained by numerical inversion with a probability-based search interval and a residual check.

Numerical integration error estimates are checked against the specified tolerances. These estimates do not constitute rigorous bounds on the actual integration error.

Interval probabilities are evaluated using differences of cumulative probabilities or complementary tails. Extremely narrow intervals can produce cancellation in finite-precision arithmetic. Consequently, a positive mathematical interval probability may be returned as zero when its numerical difference cannot be resolved. Relative accuracy is not guaranteed for arbitrarily narrow intervals or probabilities below the effective numerical resolution.

For numerical convolutions, non-boundary quantiles require a tail probability of at least the larger of 1e-8 and ten times abs_tol. This restriction does not apply to analytically evaluated Student or Cauchy distributions.

The distributions considered here are continuous, symmetric, and unimodal. Equal-tailed intervals are centred on the posterior or predictive median.

The posterior or predictive mean is reported only when the Student degrees of freedom exceed 1. Variances and standard deviations are reported only when the degrees of freedom exceed 2. Undefined moments are represented by missing values.

Directional probabilities quantify the probability that the contrast exceeds or falls below zero.

If threshold is supplied, probabilities of positive, negative, and absolute changes beyond that threshold are also calculated.

If rope is supplied, its probability content is obtained from the marginal contrast distribution. No automatic hypothesis acceptance or rejection rule is applied.

Posterior probabilities concerning population parameters must be distinguished from predictive probabilities concerning individual change scores.

No random-number generation, posterior normal approximation, or Markov chain Monte Carlo procedure is used.

Value

A named list of class babebi_contrast containing:

model

Covariance structure of the fitted model.

prior_type

Prior strategy used for inference.

target

Posterior or predictive inferential target.

contrast

Name of the contrast.

coefficients

Contrast coefficients for beta and gamma.

basis_coefficients

Contrast coefficients in the orthonormal working basis.

weight

Weight of the second rater, when applicable.

method

Distributional calculation method: "student", "cauchy", or "convolution".

df

Student degrees of freedom. For numerical convolution, these refer to the individual Student components, not to the distribution of their sum.

location

Location of the contrast distribution.

scale

Scale parameter of an analytical Student or Cauchy distribution, or NA_real_ for convolution.

component_scales

Non-negative component scales for independent Student components, when applicable.

median

Posterior or predictive median.

mean

Mean, when defined.

variance

Variance, when finite.

sd

Standard deviation, when finite.

mean_exists

Logical indicator of mean existence.

variance_exists

Logical indicator of finite variance.

level

Probability content of the equal-tailed interval.

interval

Named vector containing the lower and upper interval limits.

prob_positive

Probability that the contrast exceeds zero.

prob_negative

Probability that the contrast is below zero.

threshold

Practical relevance threshold, if supplied.

prob_above_threshold

Probability of exceeding the positive threshold.

prob_below_negative_threshold

Probability of falling below the negative threshold.

prob_abs_above_threshold

Probability that the absolute contrast exceeds the threshold.

rope

Region of practical equivalence, if supplied.

prob_rope

Probability content of the region of practical equivalence.

rel_tol

Relative numerical integration tolerance.

abs_tol

Absolute numerical integration tolerance.

subdivisions

Maximum number of integration subdivisions.

Practical relevance and equivalence probabilities are reported as NA_real_ when their corresponding arguments are omitted.

References

Kotz, S., & Nadarajah, S. (2004). Multivariate t-distributions and their applications. Cambridge University Press.

Kruschke, J. K. (2018). Rejecting or accepting parameter values in Bayesian estimation. Advances in Methods and Practices in Psychological Science, 1(2), 270-280. doi:10.1177/2515245918771304

See Also

posterior_bivariate(), draw_bivariate(), pcontrast_bivariate, qcontrast_bivariate

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    0, 0, 1, 2,
    0, 0, 2, 4,
    0, 0, 3, 1,
    0, 0, 4, 5
  )
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

post <- posterior_bivariate(
  fit,
  prior = "reference"
)

discrepancy <- contrast_bivariate(
  post,
  contrast = "discrepancy",
  threshold = 0.5,
  rope = c(-0.2, 0.2)
)

print(discrepancy)

agreement <- contrast_bivariate(
  post,
  contrast = "discrepancy",
  target = "predictive",
  rope = c(-0.2, 0.2)
)

agreement$prob_rope


Summarise a posterior contrast of ordinal latent changes

Description

Calculates posterior summaries of a linear contrast of beta and gamma on the identified latent probit response scale.

Usage

contrast_ordinal(
  fit,
  contrast,
  weight = NULL,
  level = 0.95,
  rope = NULL,
  rhat_limit = 1.01,
  ess_min = 400
)

Arguments

fit

An object returned by fit_ordinal().

contrast

Contrast name or numeric coefficient vector as specified in contrast_bivariate().

weight

Optional second-rater weight for a weighted contrast.

level

Probability content of the equal-tailed credible interval. Default is 0.95.

rope

Optional finite increasing numeric vector of length two specifying a practical equivalence region on the latent probit scale.

rhat_limit

Finite diagnostic R-hat threshold greater than one. Default is 1.01.

ess_min

Positive finite minimum effective sample size. Default is 400.

Details

Beta is the mean latent change for the reference rater. Gamma is the difference between the two mean latent changes.

The posterior summaries are empirical summaries of the retained MCMC draws. They must be interpreted in conjunction with the contrast-specific and model-wide diagnostics.

The probabilities of positive change and practical equivalence are estimated from MCMC frequencies, not independent draws. The mean MCSE does not quantify the uncertainty of these probability estimates or the credible interval endpoints.

These latent contrasts are not numerically comparable to contrasts of continuous observed change scores.

Value

A list containing the contrast coefficients, posterior mean, median, standard deviation, interval, positive and equivalence probabilities, and diagnostics.

See Also

fit_ordinal(), ordinal_diagnostics()


Draw posterior samples of agreement parameters

Description

Generates independent draws from the joint posterior of systematic between-rater discrepancy and the population variance of individual discrepancies.

Usage

draw_agreement(
  posterior,
  n_draws = 10000L,
  seed = NULL,
  content = 0.95,
  margin = NULL
)

Arguments

posterior

An object of class babebi_posterior returned by posterior_bivariate().

n_draws

Positive integer number of independent posterior draws. Default is 10000.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

content

Probability content of the conditional Gaussian population limits of agreement. Must lie strictly between 0 and 1. Default is 0.95.

margin

Optional strictly positive finite practical agreement margin. If supplied, the conditional probability of practical agreement is calculated for each draw.

Details

Under M0, M2, and M3, the population discrepancy variance has an inverse-gamma marginal posterior.

Under M1, its posterior distribution is the sum of two independent inverse-gamma variables.

Given each sampled variance, the population mean discrepancy is sampled from its conditional Gaussian posterior.

Population limits of agreement are subsequently calculated as conditional Gaussian quantiles.

Conditional practical coverage is the probability that the absolute discrepancy of a future subject is within the specified margin, conditional on each sampled pair of population mean and variance parameters.

Normal interval probabilities are evaluated using logarithmic tail probabilities. Extremely narrow intervals or probabilities below floating-point resolution may be represented as zero.

No Markov chain Monte Carlo procedure is used.

Value

A data frame with columns gamma, variance, sd, loa_lower, and loa_upper. If a practical margin is supplied, the additional column coverage contains the conditional population probability of practical agreement.

See Also

agreement_bivariate, draw_bivariate()


Generate direct posterior draws from a bivariate model

Description

Generates independent draws from the analytical joint posterior distribution returned by posterior_bivariate().

Usage

draw_bivariate(posterior, n_draws = 4000, seed = NULL, predictive = FALSE)

Arguments

posterior

An object of class babebi_posterior.

n_draws

Positive integer specifying the number of independent posterior draws. Default is 4000.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

predictive

Logical scalar indicating whether posterior predictive change scores should also be generated. Default is FALSE.

Details

Draws of the covariance parameters are followed by draws of the conditional Gaussian mean vector. Optional posterior predictive draws are generated for a new independent subject.

For models M0, M1, and M2, the free variance parameters are generated directly from inverse-gamma distributions.

For model M3, inverse-Wishart draws are generated using the Bartlett decomposition. If the upper-triangular Cholesky factor of the inverse-Wishart scale matrix is denoted by U and the lower-triangular Bartlett factor by A, the matrix F is defined as the solution to AF = U.

The covariance draw is obtained as the cross-product of F. Conditional Gaussian draws are generated by multiplying row vectors of independent standard normal variates by F.

The same covariance draw is used for the corresponding conditional mean and posterior predictive draws.

No Markov chain Monte Carlo procedure is employed. The generated posterior draws are independent, subject to the properties of the random-number generator.

A finite collection of posterior draws does not establish the existence of posterior moments. The analytical indicators mean_exists and cov_exists in the posterior object should be consulted before interpreting empirical moments.

When seed is NULL, the function uses and advances the current random-number generator state.

Value

A data frame with n_draws rows containing:

mu1

Reference-rater mean change.

mu2

Second-rater mean change.

beta

Reference-rater mean change.

gamma

Difference between the two rater-specific mean changes.

sigma1_sq

Reference-rater change-score variance.

sigma2_sq

Second-rater change-score variance.

sigma12

Covariance between the two change scores.

rho

Correlation between the two change scores.

d1_new

Predictive reference-rater change score, included when predictive = TRUE.

d2_new

Predictive second-rater change score, included when predictive = TRUE.

References

Bartlett, M. S. (1934). On the theory of statistical regression. Proceedings of the Royal Society of Edinburgh, 53, 260-283. doi:10.1017/S0370164600015637

See Also

posterior_bivariate(), bivariate_prior()

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    0, 0, 1, 2,
    0, 0, 2, 4,
    0, 0, 3, 1,
    0, 0, 4, 5
  )
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

post <- posterior_bivariate(
  fit,
  prior = bivariate_prior(
    location = c(0, 0),
    kappa = 2,
    shape = 3,
    covariance = diag(c(2, 2))
  )
)

draws <- draw_bivariate(
  post,
  n_draws = 1000,
  seed = 123,
  predictive = TRUE
)

head(draws)


Extract design parameters for Monte Carlo calibration

Description

Internal helper used to estimate sample size, mean pre-post change, and second-rater additive discrepancy from standardised user-supplied data for Monte Carlo calibration.

Usage

extract_design(data)

Arguments

data

A data frame returned by prepare_data, with columns id, time, rater, and y.

Value

A named list containing:

N

Number of unique subjects.

delta

Estimated mean pre-post change, averaged across raters.

bias_r2

Estimated mean additive discrepancy of the second rater relative to the reference rater, averaged across subjects and time points.

time_levels

The two ordered time levels used in the data.

rater_levels

The two ordered rater levels used in the data.


Fit a bivariate change-score model to observed data

Description

Fits a Gaussian bivariate model to a fully observed 2 (time) x 2 (rater) repeated-measures dataset. Subject-specific pre-post change scores are represented as paired observations, allowing the covariance structure of the two raters' changes to be modelled explicitly.

Usage

fit_bivariate(
  data,
  id,
  time,
  rater,
  outcome,
  model,
  time_order = NULL,
  rater_order = NULL
)

Arguments

data

A data frame in long format.

id

Unquoted column name identifying subjects or a character string.

time

Unquoted column name identifying time points or a character string.

rater

Unquoted column name identifying raters or a character string.

outcome

Unquoted column name containing the observed score or a character string. Scores must be finite and numeric.

model

Character string specifying the covariance structure. Available models are "M0", "M1", "M2", and "M3". The covariance structure must be specified explicitly.

time_order

Optional character vector of length 2 giving the order of the time factor: baseline first, follow-up second.

rater_order

Optional character vector of length 2 giving the order of the rater factor: reference rater first, second rater second.

Details

The mean structure retains the reference-rater parametrisation of the original babebi model. The first parameter represents the mean change recorded by the reference rater, and the second represents the difference between the mean changes recorded by the two raters.

Parameter estimation is based on closed-form maximum likelihood solutions. No posterior approximation or random-number generation is used.

Each subject contributes a bivariate observation comprising the follow-up minus baseline change scores recorded by the two raters. Subjects are assumed to be independent and identically distributed according to a bivariate normal distribution.

The mean vector is parametrised as \mu = (\beta, \beta + \gamma)^{T}, where \beta denotes the reference-rater mean change and \gamma denotes the second-rater mean change minus the reference-rater mean change.

Four covariance structures are available:

M0

Independent homoscedastic model. The two raters have equal change-score variances and zero covariance.

M1

Independent heteroscedastic model. The two raters have separate change-score variances and zero covariance.

M2

Correlated homoscedastic model. The two raters have equal change-score variances and an unrestricted correlation within the positive-definite parameter space.

M3

Correlated heteroscedastic model. The two raters have separate change-score variances and an unrestricted correlation within the positive-definite parameter space.

For all four covariance structures, the maximum likelihood estimate of the mean vector is the vector of observed rater-specific mean changes.

Let W denote the centred sum-of-squares and cross-products matrix of the paired change scores. The unconstrained maximum likelihood covariance estimate is W/N, where N is the number of subjects. The sample covariance matrix, computed as W/(N-1), is also returned.

The covariance matrix of the regression parameter estimates is obtained by applying the linear transformation from rater-specific means to the reference-rater parametrisation. Substitution of the estimated covariance matrix provides a plug-in estimate of the sampling covariance.

A minimum of two subjects is required. For model M3, a positive-definite maximum likelihood covariance estimate requires at least three subjects and a centred change-score matrix of rank two.

When the covariance estimate is singular or numerically ill-conditioned, the function retains the observed change scores, mean estimates, and sufficient statistics. The maximum likelihood covariance and the maximised log-likelihood are then reported as unavailable.

Numerical conditioning is assessed using the reciprocal condition number of the covariance estimate after scalar rescaling. Covariance estimates with a reciprocal condition number no greater than sqrt(.Machine$double.eps) are not used for subsequent calculations. No diagonal adjustment or covariance regularisation is applied.

Model M0 has the same Gaussian mean and covariance structure as the original babebi model. Its maximum likelihood variance estimate uses the denominator 2N, whereas the original estimation procedure uses a residual degrees-of-freedom correction with denominator 2N - 2.

This function provides a likelihood-based statistical foundation for subsequent inference. It does not compute posterior distributions, credible intervals, posterior probabilities, or Bayes factors.

The parameter gamma represents disagreement in mean change. It does not identify absolute rater bias or disagreement at the individual subject level.

Value

A named list of class babebi_bivariate containing:

model

The selected covariance structure.

N

Number of independent subjects.

changes

An N by 2 numeric matrix of paired change scores, with subjects in rows and raters in columns.

mu_hat

Named numeric vector of rater-specific mean changes.

theta_hat

Named numeric vector containing the reference-rater mean change (beta) and the between-rater difference in mean change (gamma).

scatter

Centred sum-of-squares and cross-products matrix.

sample_cov

Sample covariance matrix with denominator N - 1.

sigma_ml

Maximum likelihood covariance matrix under the selected model, or NULL when unavailable.

cov_theta_ml

Plug-in sampling covariance matrix of the parameter estimates, or NULL when unavailable.

loglik

Maximised Gaussian log-likelihood, or NA_real_ when a numerically usable maximum likelihood solution is unavailable.

npar

Number of free parameters in the selected model, including the two mean parameters.

rcond

Reciprocal condition number of the rescaled covariance estimate, or NA_real_ when unavailable.

status

Character string equal to "ok" when the maximum likelihood solution is available or "covariance_unavailable" otherwise.

time_levels

The two ordered time levels.

rater_levels

The two ordered rater levels.

References

Anderson, T. W. (2003). An introduction to multivariate statistical analysis (3rd ed.). John Wiley & Sons.

See Also

fit_model()

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    3.0, 3.2, 3.8, 4.0,
    2.9, 3.1, 3.5, 3.7,
    3.4, 3.6, 4.0, 4.1,
    3.1, 3.3, 3.9, 4.0
  )
)

fit <- fit_bivariate(
  data = dat,
  id = id,
  time = time,
  rater = rater,
  outcome = y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

print(fit)
fit$theta_hat
fit$sigma_ml
fit$cov_theta_ml
stats::logLik(fit)


Fit the babebi model to observed data

Description

Fits the current babebi model to a fully observed 2 (time) x 2 (rater) repeated-measures dataset. Estimation is based on difference scores and a linear model including a rater indicator as covariate.

Usage

fit_model(
  data,
  id,
  time,
  rater,
  outcome,
  time_order = NULL,
  rater_order = NULL,
  n_draws = 4000,
  seed = NULL
)

Arguments

data

A data frame in long format.

id

Unquoted column name identifying subjects or a character string.

time

Unquoted column name identifying time points or a character string.

rater

Unquoted column name identifying raters or a character string.

outcome

Unquoted column name containing the observed score or a character string.

time_order

Optional character vector of length 2 giving the order of the time factor: baseline first, follow-up second.

rater_order

Optional character vector of length 2 giving the order of the rater factor: reference rater first, second rater second.

n_draws

Number of posterior draws used for approximation.

seed

Optional integer seed used to initialise the random-number generator for posterior sampling.

Details

Posterior draws are obtained from a large-sample normal approximation to the posterior of the regression coefficients under an improper flat prior.

This historical workflow assumes independent Gaussian change scores with a common residual variance. It uses a flat coefficient prior conditional on a plug-in variance estimate, not the exact marginal posterior with unknown variance. The BIC approximation is for zero reference-rater mean change with the rater term retained; it is not a marginal likelihood under the improper coefficient prior. For dependence, exact conjugate inference and appropriate proper-prior evidence, see fit_bivariate(), posterior_bivariate() and bayesfactor_bivariate().

Historical numerical safeguards and degenerate cases. Use finite real-valued outcomes and finite change scores; the basic input checks reject missing values but do not explicitly reject all infinite values. At least two participants are required for residual variance estimation.

The basic fit adds 1e-10 to each diagonal element of the estimated coefficient covariance matrix before Cholesky decomposition. With zero pooled within-rater residual variance (for example, constant change within each rater), this produces artificial posterior dispersion. With very small variances, the fixed addition may materially affect the reported uncertainty. It is a numerical safeguard, not a prior or an estimate of sampling uncertainty.

For the BIC-based Bayes factor, each residual sum of squares is bounded below by .Machine$double.eps (approximately 2.22e-16 in double precision). When this bound is active, the result is a regularised numerical approximation to BIC. At zero residual variance, the ordinary Gaussian maximum likelihood calculation is degenerate. These fixed safeguards are scale-dependent and are also used in the historical Monte Carlo engine.

Do not interpret basic intervals, posterior probabilities or Bayes factors from degenerate or numerically dominated fits as reliable inferential evidence. Inspect change scores and residual variability, check the measurement scale, and consider the advanced framework with a scientifically justified proper prior where appropriate. The safeguards remain unchanged for backward compatibility.

Value

A named list of class babebi_fit.

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    3.0, 3.2, 3.8, 4.0,
    2.9, 3.1, 3.5, 3.7,
    3.4, 3.6, 4.0, 4.1,
    3.1, 3.3, 3.9, 4.0
  )
)

fit <- fit_model(
  data = dat,
  id = id,
  time = time,
  rater = rater,
  outcome = y,
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2"),
  n_draws = 500,
  seed = 123
)

print(fit)
summary(fit)
plot(fit)


Fit a hierarchical ordinal probit model

Description

Estimates a Bayesian cumulative probit model for a complete two-time, two-rater repeated-measures design.

Usage

fit_ordinal(
  data,
  id,
  time,
  rater,
  outcome,
  category_order,
  time_order,
  rater_order,
  prior,
  chains = 4L,
  warmup = 1000L,
  draws = 2000L,
  seed = NULL
)

Arguments

data

Long-format data frame.

id

Subject identifier column, supplied as an unquoted name or character string.

time

Time column, supplied as an unquoted name or character string.

rater

Rater column, supplied as an unquoted name or character string.

outcome

Ordinal outcome column, supplied as an unquoted name or character string.

category_order

Explicit ordered vector of all outcome categories, from lowest to highest. Unobserved categories may be included.

time_order

Explicit vector of length two identifying baseline and follow-up, in this order.

rater_order

Explicit vector of length two identifying reference and second raters, in this order.

prior

Proper prior returned by ordinal_prior().

chains

Integer number of independently initialised chains, at least two. Default is four.

warmup

Non-negative integer number of discarded Gibbs iterations per chain. Default is 1000.

draws

Integer number of retained iterations per chain, at least 20. Default is 2000.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

Details

The latent response has fixed effects for baseline location, rater, time, and the time-by-rater interaction, and bivariate Gaussian subject-specific occasion effects.

Conditional residuals are independent standard Gaussian variables. The first finite cutpoint is fixed at zero. All cutpoints are shared across times and raters.

The model assumes threshold invariance. It does not test general psychometric measurement invariance.

The fixed effects concern the latent response underlying the observed ordinal outcome. They do not automatically identify changes in an underlying psychological construct.

The occasion effects induce dependence both within an occasion and between occasions. This model restricts the two latent change-score variances to be equal and their covariance to be non-negative.

Posterior sampling uses data augmentation with Gibbs updates for the latent responses, fixed effects, random effects, random-effect covariance, and free cutpoints.

Missing values and incomplete or duplicated subject cells are not supported. All subjects must contribute exactly one response for each time-by-rater combination.

Empty outcome categories are allowed because the priors are proper. Their corresponding cutpoints can be weakly informed by the observations.

The retained draws are autocorrelated MCMC samples. Check ordinal_diagnostics() before interpreting summaries. A completed sampling run does not establish convergence.

Value

A list of class babebi_ordinal containing:

N, K

Number of subjects and outcome categories.

category_order, time_order, rater_order

Original labels.

data

Canonical data with integer category codes.

counts

Observed category frequencies by design cell.

prior

Validated prior specification.

chains, warmup, n_draws, seed

Sampling settings.

draws

Array indexed by retained iteration, chain, and parameter. The fixed first cutpoint is not stored.

References

Albert, J. H., & Chib, S. (1993). Bayesian analysis of binary and polychotomous response data. Journal of the American Statistical Association, 88(422), 669-679. doi:10.1080/01621459.1993.10476321

Liu, Y., Millsap, R. E., West, S. G., Tein, J.-Y., Tanaka, R., & Grimm, K. J. (2017). Testing measurement invariance in longitudinal data with ordered-categorical measures. Psychological Methods, 22(3), 486-506. doi:10.1037/met0000075

See Also

ordinal_prior(), ordinal_diagnostics(), contrast_ordinal(), predict_ordinal()

Examples

dat <- simulate_ordinal(
  N = 8, coefficients = c(0, 0, 0.5, 0.2),
  random_covariance = diag(2),
  cutpoints = c(0, 1),
  category_order = c("low", "medium", "high"),
  seed = 123
)

prior <- ordinal_prior(
  rep(0, 4), rep(1, 4), 6, diag(2),
  cutpoint_mean = 1, cutpoint_sd = 0.5
)

# Short illustrative run; not sufficient for substantive inference.
fit <- fit_ordinal(
  dat, id, time, rater, y,
  category_order = c("low", "medium", "high"),
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2"),
  prior = prior, chains = 2, warmup = 20,
  draws = 30, seed = 123
)

ordinal_diagnostics(fit)


Extract the log-likelihood of a babebi bivariate model

Description

Returns the maximised Gaussian log-likelihood of a fitted bivariate change-score model.

Usage

## S3 method for class 'babebi_bivariate'
logLik(object, ...)

Arguments

object

An object of class babebi_bivariate.

...

Further arguments passed to or from other methods.

Details

The number of observations corresponds to the number of independent subjects, not the total number of scalar change scores.

An error is returned when a numerically usable maximum likelihood covariance estimate is unavailable.

Value

An object of class logLik, with attributes df and nobs giving the number of free model parameters and the number of independent subjects, respectively.


Compute the log marginal likelihood of a bivariate model

Description

Computes the analytical log marginal likelihood of a Gaussian bivariate change-score model under a proper conjugate prior.

Usage

log_marginal_bivariate(posterior)

Arguments

posterior

An object of class babebi_posterior returned by posterior_bivariate() under a proper conjugate prior.

Details

The calculation integrates over both the mean parameters and the covariance parameters using the posterior hyperparameters returned by posterior_bivariate().

The marginal likelihood is the integral of the sampling likelihood with respect to the normalised prior distribution.

For models M0, M1, and M2, the marginal likelihood is obtained from the normal-inverse-gamma normalising constants.

Model M0 contains one common variance parameter. Models M1 and M2 contain two independent variance parameters in their respective orthonormal working bases.

The orthonormal transformation used for model M2 has an absolute Jacobian determinant of one.

For model M3, the marginal likelihood is obtained from the normal-inverse-Wishart normalising constants, including the multivariate gamma function.

All normalising constants of the sampling likelihood are retained, allowing marginal likelihoods to be compared across the four covariance structures for the same observed data.

Calculations are performed on the natural logarithmic scale.

A maximum likelihood covariance estimate need not be available. A proper conjugate posterior may support marginal likelihood calculations even when the observed scatter matrix is singular.

Improper reference priors are not supported because their arbitrary normalising constants preclude ordinary marginal likelihood comparisons.

Value

A finite numeric scalar containing the natural logarithm of the marginal likelihood.

References

Kass, R. E., & Raftery, A. E. (1995). Bayes factors. Journal of the American Statistical Association, 90(430), 773-795. doi:10.1080/01621459.1995.10476572

Murphy, K. P. (2007). Conjugate Bayesian analysis of the Gaussian distribution. Technical report.

See Also

posterior_bivariate(), bivariate_prior(), compare_bivariate

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), 4),
  rater = rep(c("r1", "r2"), 8),
  y = c(0, 0, 1, 2,
        0, 0, 2, 4,
        0, 0, 3, 1,
        0, 0, 4, 5)
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

prior <- bivariate_prior(
  location = c(0, 0),
  kappa = 2,
  shape = 3,
  covariance = diag(c(2, 2))
)

post <- posterior_bivariate(fit, prior)

log_marginal_bivariate(post)


Run Monte Carlo calibration from user-supplied data

Description

Uses observed data to estimate the sample size, mean pre-post change, and mean additive discrepancy of the second rater for the Monte Carlo engine, then runs a single Monte Carlo validation cell.

Usage

montecarlo_from_data(
  data,
  id,
  time,
  rater,
  outcome,
  time_order = NULL,
  rater_order = NULL,
  R = 1000,
  N = NULL,
  delta = NULL,
  bias_r2 = NULL,
  seed = NULL
)

Arguments

data

A data frame in long format.

id

Unquoted column name identifying subjects or a character string.

time

Unquoted column name identifying time points or a character string.

rater

Unquoted column name identifying raters or a character string.

outcome

Unquoted column name containing the observed score or a character string.

time_order

Optional character vector of length 2 giving the order of the time factor: baseline first, follow-up second.

rater_order

Optional character vector of length 2 giving the order of the rater factor: reference rater first, second rater second.

R

Number of Monte Carlo repetitions.

N

Optional override for the sample size used in the simulation. Defaults to the observed number of subjects.

delta

Optional override for the pre-post effect used in the simulation. Defaults to the value estimated from the data.

bias_r2

Optional override for the additive bias of the second rater. Defaults to the value estimated from the data.

seed

Optional integer seed used to initialise the random-number generator for simulation.

Details

The original simulation uses independent unit-variance change scores. Its default delta is the average observed change across raters, while bias_r2 is the mean difference in rating levels across occasions. These are historical calibration inputs, not necessarily the reference-rater change and discrepancy between changes. It does not reproduce the observed change-score covariance. Use scenario_from_fit() and validate_bivariate() for comparative evaluation of a paired change-score mechanism.

Value

A one-row data frame of class babebi_validation with Monte Carlo performance summaries. The attributes calibrated_design and call store the design estimated from the observed data and the original call.

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    3.0, 3.2, 3.8, 4.0,
    2.9, 3.1, 3.5, 3.7,
    3.4, 3.6, 4.0, 4.1,
    3.1, 3.3, 3.9, 4.0
  )
)

mc <- montecarlo_from_data(
  data = dat,
  id = id,
  time = time,
  rater = rater,
  outcome = y,
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2"),
  R = 100,
  seed = 123
)

print(mc)


Assess MCMC diagnostics for an ordinal model

Description

Computes rank-normalised and folded split R-hat, bulk and tail effective sample sizes, and Monte Carlo standard errors of posterior means.

Usage

ordinal_diagnostics(fit, rhat_limit = 1.01, ess_min = 400)

Arguments

fit

An object returned by fit_ordinal().

rhat_limit

Finite R-hat threshold greater than one. Default is 1.01.

ess_min

Positive finite minimum effective sample size. Default is 400.

Details

Each chain is split into two equal segments, discarding its central iteration if the retained length is odd.

R-hat is the maximum of rank-normalised and folded rank-normalised split R-hat.

Effective sample sizes use pooled autocorrelation estimates and an initial positive, monotone sequence of paired autocorrelations. ESS is conservatively capped at the number of split-chain draws.

Bulk ESS is calculated from rank-normalised draws. Tail ESS is the minimum ESS of the indicator sequences at the pooled fifth and ninety-fifth percentiles.

Mean MCSE uses the posterior standard deviation divided by the square root of the ESS of the untransformed draws.

These diagnostics are an internal implementation of the corresponding diagnostic principles, not a claim of numerical identity with other software packages.

Undefined diagnostics are reported as NA. An adequate diagnostic flag is not proof of convergence.

Value

A data frame with parameter names, R-hat, bulk ESS, tail ESS, mean ESS, mean MCSE, and an adequacy indicator.

References

Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Burkner, P.-C. (2021). Rank-normalization, folding, and localization: An improved R-hat for assessing convergence of MCMC (with discussion). Bayesian Analysis, 16(2), 667-718. doi:10.1214/20-BA1221

See Also

fit_ordinal(), contrast_ordinal()


Specify proper priors for hierarchical ordinal probit inference

Description

Defines proper priors for the fixed coefficients, covariance of the subject-specific occasion effects, and ordered cutpoints.

Usage

ordinal_prior(
  coefficient_mean,
  coefficient_sd,
  random_df,
  random_covariance,
  cutpoint_mean = numeric(0),
  cutpoint_sd = numeric(0)
)

Arguments

coefficient_mean

Finite numeric vector of length four. Prior locations for alpha, delta, beta, and gamma, in this order.

coefficient_sd

Strictly positive finite numeric vector of length four. Prior standard deviations for the coefficients.

random_df

Finite inverse-Wishart degrees of freedom, strictly greater than three.

random_covariance

Symmetric positive-definite 2 by 2 prior expectation of the occasion-effect covariance matrix.

cutpoint_mean

Strictly increasing positive finite numeric vector of locations for the free cutpoints. Use numeric(0) for a binary outcome.

cutpoint_sd

Positive finite numeric vector of standard deviations for the free cutpoints, of the same length as cutpoint_mean.

Details

The coefficients have independent Gaussian priors. Their order is alpha, delta, beta, gamma.

Alpha is the reference-rater baseline location; delta is the baseline rater discrepancy; beta is the reference-rater change; gamma is the between-rater discrepancy in mean change.

The random-effect covariance has an inverse-Wishart prior. Its scale matrix is (random_df - 3) times random_covariance.

The first finite cutpoint is fixed at zero. The remaining cutpoints have a product of Gaussian prior densities conditioned on strict positive ordering. Their specified locations and scales are those of the underlying Gaussian densities, not the marginal moments after conditioning.

The number of outcome categories is two plus the number of free cutpoints.

All prior components are mutually independent before imposing the ordering constraint on the free cutpoints.

No default prior is assigned to the coefficients or covariance.

Value

A named list of class babebi_ordinal_prior.

See Also

fit_ordinal(), simulate_ordinal()

Examples

prior <- ordinal_prior(
  coefficient_mean = rep(0, 4),
  coefficient_sd = rep(1, 4),
  random_df = 6,
  random_covariance = diag(2),
  cutpoint_mean = c(1, 2),
  cutpoint_sd = c(0.5, 0.5)
)


Evaluate a marginal contrast distribution

Description

Evaluates cumulative or upper-tail probabilities and quantiles of a posterior or predictive contrast distribution returned by contrast_bivariate.

Usage

pcontrast_bivariate(q, object, lower.tail = TRUE)

qcontrast_bivariate(p, object, lower.tail = TRUE)

Arguments

q

Numeric vector of quantiles. Infinite values are permitted; missing values are not permitted.

object

An object of class babebi_contrast.

lower.tail

Logical scalar. If TRUE, probabilities refer to the lower tail. If FALSE, probabilities refer to the upper tail.

p

Numeric vector of probabilities between 0 and 1. Missing values are not permitted.

Details

Analytical Student and Cauchy distributions are evaluated using the corresponding functions in the stats package. Other two-component distributions are evaluated through deterministic numerical convolution.

For numerical convolutions, tail probabilities are evaluated directly using the symmetry of the centred distribution.

Numerical quantiles are obtained by inverting the corresponding tail probability. Non-boundary probabilities must be sufficiently separated from 0 and 1, as described in contrast_bivariate.

The probability tolerances stored in object are used for numerical convolution and inversion. Relative accuracy is not guaranteed for probabilities smaller than the absolute integration tolerance.

Boundary probabilities of 0 and 1 return the corresponding infinite quantiles. Infinite quantiles return the corresponding boundary probabilities.

No random numbers are generated.

Value

A numeric vector of probabilities for pcontrast_bivariate() or quantiles for qcontrast_bivariate(), with length equal to that of the input vector.

See Also

contrast_bivariate, stats::pt(), stats::qt(), stats::integrate()

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    0, 0, 1, 2,
    0, 0, 2, 4,
    0, 0, 3, 1,
    0, 0, 4, 5
  )
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M1",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

post <- posterior_bivariate(
  fit,
  prior = "reference"
)

discrepancy <- contrast_bivariate(
  post,
  contrast = "discrepancy"
)

pcontrast_bivariate(
  c(-0.5, 0, 0.5),
  discrepancy
)

qcontrast_bivariate(
  c(0.025, 0.5, 0.975),
  discrepancy
)


Plot agreement between paired change scores

Description

Produces a Bland-Altman representation of the individual discrepancies against the arithmetic means of the two raters' observed change scores.

Usage

## S3 method for class 'babebi_agreement'
plot(
  x,
  limits = "predictive",
  show_margin = TRUE,
  show_legend = TRUE,
  xlab = "Mean of the two change scores",
  ylab = "Second-rater minus reference-rater change",
  main = "Agreement between paired change scores",
  ylim = NULL,
  pch = 19,
  ...
)

Arguments

x

An object of class babebi_agreement.

limits

Character string identifying the interval displayed on the plot. One of "predictive" (default), "conditional", or "descriptive".

show_margin

Logical scalar indicating whether the practical agreement margins should be displayed when available. Default is TRUE.

show_legend

Logical scalar indicating whether a legend should be displayed. Default is TRUE.

xlab

Horizontal axis label.

ylab

Vertical axis label.

main

Plot title.

ylim

Optional vertical axis limits.

pch

Plotting character for individual subjects.

...

Further graphical arguments passed to graphics::plot().

Details

With limits = "predictive", the displayed limits are the equal-tailed posterior predictive interval for a new subject's discrepancy.

With limits = "conditional", the displayed limits are the marginal posterior medians of the two conditional population limits of agreement. These do not necessarily define an interval with the nominal predictive content.

With limits = "descriptive", the displayed limits are the sample mean plus and minus the specified standard normal quantile multiplied by the sample standard deviation of the observed discrepancies.

The reference line at zero denotes exact equality of the two observed changes.

Practical margins are displayed separately from the statistical interval limits.

Value

The input object, invisibly.


Plot a babebi fit object

Description

Plot a babebi fit object

Usage

## S3 method for class 'babebi_fit'
plot(x, ...)

Arguments

x

An object of class babebi_fit.

...

Further arguments passed to or from other methods.

Value

No return value, called for its side effects.


Obtain the exact posterior of a bivariate change-score model

Description

Computes analytical posterior distributions for the four Gaussian covariance structures available in fit_bivariate().

Usage

posterior_bivariate(fit, prior)

Arguments

fit

An object of class babebi_bivariate returned by fit_bivariate().

prior

Either the character string "reference" or an object of class babebi_prior returned by bivariate_prior(). The prior specification must be supplied explicitly.

Details

Posterior updating is based on the sample size, observed mean vector, and centred sum-of-squares and cross-products matrix. The uncertainty associated with the covariance parameters is incorporated into posterior inference.

Two prior strategies are available:

Reference prior

An improper prior with a constant density for the mean parameters and an independence Jeffreys-type prior for the covariance parameters. Posterior propriety is checked before inference.

Proper conjugate prior

A normal-inverse-gamma or normal-inverse-Wishart prior specified through bivariate_prior().

For the reference prior, the variance density is proportional to the reciprocal of the common variance in model M0. For models M1 and M2, it is proportional to the product of the reciprocals of the two free variances in the appropriate orthonormal basis.

For model M3, the reference prior density is proportional to |\Sigma|^{-3/2} with respect to the distinct covariance elements and the mean parameters.

The reference prior is one particular objective prior specification. It is not asserted to be universally optimal for all inferential targets.

Under models M0 and M3, the marginal posterior distribution of the mean vector is multivariate Student.

Under models M1 and M2, the marginal distribution is a product of independent univariate Student distributions in the appropriate orthonormal basis.

For model M2, the basis vectors correspond to the normalised sum and difference of the two rater-specific changes.

The Student scale matrices are distinguished from covariance matrices. A Student distribution has a finite mean when its degrees of freedom exceed 1 and a finite covariance when its degrees of freedom exceed 2.

Posterior moments that do not exist are reported as missing values. The posterior location remains available.

The posterior predictive distribution concerns the paired change scores of a new independent subject from the same population.

A maximum likelihood covariance estimate need not be available in fit. A proper conjugate prior may permit posterior inference when the observed scatter matrix is singular.

Positive-definite matrix calculations use scalar rescaling and Cholesky decomposition. A reciprocal condition number no greater than sqrt(.Machine$double.eps) is treated as numerically unsuitable for unrestricted matrix calculations. No diagonal adjustment is applied.

The function computes analytical posterior quantities and does not generate random numbers. Posterior draws may be obtained through draw_bivariate().

The function does not compute Bayes factors. In particular, the improper reference prior does not define an ordinary marginal likelihood.

Value

A named list of class babebi_posterior containing:

model

The fitted covariance structure.

N

Number of independent subjects.

fit

The original bivariate model object.

prior

The prior specification used for inference.

prior_type

Either "reference" or "proper".

kappa

Posterior conditional precision multiplier.

hyperparameters

Posterior covariance hyperparameters. For M0, M1, and M2, these are the inverse-gamma shape and scale. For M3, they are the inverse-Wishart degrees of freedom and scale matrix.

family

Either "multivariate_t" or "independent_t".

df

Marginal Student degrees of freedom.

basis

Orthonormal transformation matrix from the working basis to the rater-specific mean parametrisation.

location_basis

Posterior location in the working basis.

location_mu

Posterior location of the rater-specific mean changes.

location_theta

Posterior location of beta and gamma.

scale_mean

Student scale matrix in the working basis. For independent Student components, the diagonal elements specify their separate squared scale parameters.

scale_predictive

Predictive Student scale matrix in the working basis.

mean_exists

Logical indicator of the existence of the marginal posterior mean.

cov_exists

Logical indicator of the existence of the marginal posterior covariance.

mean_mu

Posterior mean of the rater-specific mean changes, when defined.

mean_theta

Posterior mean of beta and gamma, when defined.

mean_sigma

Posterior expected covariance matrix of the paired change scores, when finite.

cov_mu

Posterior covariance matrix of the rater-specific mean changes, when finite.

cov_theta

Posterior covariance matrix of beta and gamma, when finite.

mean_predictive

Predictive mean vector, when defined.

cov_predictive

Predictive covariance matrix, when finite.

References

Berger, J. O., & Sun, D. (2008). Objective priors for the bivariate normal model. The Annals of Statistics, 36(2), 963-982. doi:10.1214/07-AOS501

Murphy, K. P. (2007). Conjugate Bayesian analysis of the Gaussian distribution. Technical report.

See Also

fit_bivariate(), bivariate_prior(), draw_bivariate()

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), times = 4),
  rater = rep(c("r1", "r2"), times = 8),
  y = c(
    0, 0, 1, 2,
    0, 0, 2, 4,
    0, 0, 3, 1,
    0, 0, 4, 5
  )
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

reference <- posterior_bivariate(
  fit,
  prior = "reference"
)

proper <- posterior_bivariate(
  fit,
  prior = bivariate_prior(
    location = c(0, 0),
    kappa = 2,
    shape = 3,
    covariance = diag(c(2, 2))
  )
)

print(reference)
print(proper)
proper$mean_theta
proper$cov_theta


Predict ordinal category probabilities for a new subject

Description

Summarises the population-marginal category probabilities and changes in exceedance probabilities for both raters.

Usage

predict_ordinal(fit, level = 0.95)

Arguments

fit

An object returned by fit_ordinal().

level

Probability content of the marginal credible intervals. Default is 0.95.

Details

The subject-specific occasion effects are integrated out analytically conditional on each posterior parameter draw.

The marginal latent variance at each occasion is one plus the corresponding occasion-effect variance.

Category probabilities are calculated as differences of Gaussian cumulative probabilities.

Exceedance changes compare the marginal probability of attaining at least a specified category at follow-up with the corresponding probability at baseline.

The difference in exceedance changes is the second-rater change minus the reference-rater change.

These marginal contrasts do not represent probabilities of individual transitions or individual improvement.

The returned intervals concern posterior uncertainty in population probabilities, not individual prediction intervals. Check the model-wide MCMC diagnostics before interpretation.

Value

A list containing the interval level, a data frame of category probabilities by time and rater, and a data frame of exceedance-probability changes by category.

See Also

fit_ordinal(), contrast_ordinal()


Standardise user data for babebi

Description

Internal helper used to convert user-supplied data into the format required by the estimation and Monte Carlo engine.

Usage

prepare_data(
  data,
  id,
  time,
  rater,
  outcome,
  time_order = NULL,
  rater_order = NULL
)

Arguments

data

A data frame in long format.

id

Unquoted column name identifying subjects or a character string.

time

Unquoted column name identifying time points or a character string.

rater

Unquoted column name identifying raters or a character string.

outcome

Unquoted column name containing the observed score or a character string.

time_order

Optional character vector of length 2 specifying the order of the time factor (e.g., c("pre", "post")).

rater_order

Optional character vector of length 2 specifying the order of the rater factor (reference rater first).

Details

The function assumes a fully observed 2 (time) × 2 (rater) repeated-measures design. Each subject must contribute exactly one observation for each combination of time point and rater.

If time_order or rater_order are not provided, the ordering of factor levels follows the order of appearance in the data. Users are encouraged to specify these arguments explicitly when the ordering carries substantive meaning (e.g., pre vs post).

Value

A data frame with four standardised columns: id, time, rater, and y.


Print a Bayesian agreement analysis

Description

Prints descriptive agreement summaries, posterior parameter summaries, posterior predictive limits, and practical agreement probabilities.

Usage

## S3 method for class 'babebi_agreement'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_agreement.

digits

Number of decimal places used to display numeric results.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a babebi bivariate model object

Description

Prints the selected covariance structure, sample size, mean change estimates, estimated covariance matrix, and maximised log-likelihood, when available.

Usage

## S3 method for class 'babebi_bivariate'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_bivariate.

digits

Number of digits used to display numeric results.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a babebi contrast object

Description

Prints the inferential target, contrast specification, marginal distributional method, location, moments, equal-tailed interval, directional probabilities, and optional practical relevance and equivalence probabilities.

Usage

## S3 method for class 'babebi_contrast'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_contrast.

digits

Number of digits used to display numeric results.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a babebi fit object

Description

Print a babebi fit object

Usage

## S3 method for class 'babebi_fit'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_fit.

digits

Number of digits to print.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a babebi posterior object

Description

Prints the fitted covariance structure, prior specification, marginal posterior family, Student degrees of freedom, posterior location, and analytical posterior moments, when available.

Usage

## S3 method for class 'babebi_posterior'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_posterior.

digits

Number of digits used to display numeric results.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a babebi validation object

Description

Print a babebi validation object

Usage

## S3 method for class 'babebi_validation'
print(x, digits = 3, ...)

Arguments

x

An object of class babebi_validation.

digits

Number of digits to print.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Print a summary of a babebi fit object

Description

Print a summary of a babebi fit object

Usage

## S3 method for class 'summary.babebi_fit'
print(x, ...)

Arguments

x

An object of class summary.babebi_fit.

...

Further arguments passed to or from other methods.

Value

The input object, invisibly.


Resolve a column name supplied as symbol or character string

Description

Internal helper for functions that accept either unquoted column names or character strings.

Usage

resolve_colname(expr, env = parent.frame())

Arguments

expr

A captured expression representing a column name.

env

The environment in which the expression should be resolved.

Value

A character string of length 1.


Run one Monte Carlo validation cell

Description

Internal helper used to evaluate the analytical babebi model under a single simulation condition defined by sample size, pre-post effect, and rater bias.

Usage

run_cell(N, delta, bias_r2, R)

Arguments

N

Integer sample size.

delta

Numeric pre-post effect for the reference rater.

bias_r2

Numeric additive discrepancy for the second rater.

R

Integer number of Monte Carlo repetitions.

Details

The current implementation simulates pre-post difference scores directly for the reference rater and the second rater, then applies the same analytical linear-model logic used in fit_model().

Value

A one-row data frame with columns N, delta, bias_r2, bias, rmse, coverage, ppos_mean, and bf_mean.


Perform simulation-based calibration of bivariate Bayesian inference

Description

Evaluates prior-predictive calibration of the conjugate Bayesian inference and posterior sampling procedures.

Usage

sbc_bivariate(
  N,
  model,
  prior,
  contrast,
  weight = NULL,
  R = 100L,
  n_draws = 200L,
  bins = 10L,
  seed = NULL,
  rel_tol = 1e-08,
  abs_tol = 1e-10,
  subdivisions = 1000L
)

Arguments

N

Integer number of subjects per simulated dataset. Must be at least two.

model

Covariance structure, one of "M0", "M1", "M2", or "M3".

prior

Proper conjugate prior returned by bivariate_prior(), compatible with the covariance structure.

contrast

Contrast name or numeric coefficient vector as specified in contrast_bivariate().

weight

Optional second-rater weight for a weighted contrast.

R

Number of independent prior-predictive repetitions. An integer of at least two. Default is 100.

n_draws

Number of independent posterior draws per repetition. An integer of at least 20. Default is 200.

bins

Number of histogram bins. Must be at least two and not exceed n_draws + 1. Default is 10.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

rel_tol

Relative integration tolerance passed to contrast_bivariate().

abs_tol

Absolute integration tolerance passed to contrast_bivariate().

subdivisions

Maximum number of integration subdivisions.

Details

Each repetition independently generates covariance and mean parameters from the proper conjugate prior, then generates Gaussian paired change scores conditional on these parameters.

The generated data are analysed using the same prior and covariance structure.

For model M3, the prior covariance is generated by sampling the precision matrix from a Wishart distribution and subsequently inverting it. This differs from the posterior sampling algorithm in draw_bivariate().

The function calculates posterior ranks for the selected mean contrast and the population variance of individual discrepancies using draw_bivariate().

An additional discrepancy variance rank is calculated using the independently implemented draw_agreement() sampler.

Ties are resolved by randomising uniformly among the possible ranks associated with equal values.

The posterior cumulative distribution function of the mean contrast is evaluated at its generated parameter value.

Under correct prior-predictive calibration, the posterior ranks are discrete uniform and the cumulative distribution function values are continuous uniform.

Histogram expectations for the discrete ranks account for the exact number of possible ranks assigned to each bin.

Failed posterior analyses are retained with diagnostic messages. A fatal failure during prior or data generation stops the simulation.

Histogram counts use available repetitions only. Uniform reference expectations are not generally justified after parameter-dependent exclusions; failure rates must be examined before interpreting the histograms.

The function provides diagnostic results without imposing automatic pass-fail decisions based on uniformity tests.

Marginal rank uniformity is a necessary calibration property, but does not establish correctness of the complete joint posterior distribution.

The procedure does not evaluate robustness to model misspecification, and does not establish frequentist coverage at every fixed parameter value.

Improper reference priors cannot be sampled and are not supported by this procedure.

Value

A named list of class babebi_sbc containing:

model, prior, N, R, n_draws, bins, seed

Simulation settings and prior specification.

coefficients

Selected contrast coefficients.

replicates

Generated parameter values, posterior ranks, posterior cumulative probability, computational status, warnings, and error messages.

histograms

Observed bin counts and discrete or continuous uniform reference probabilities.

n_success, n_failed

Numbers of successful and unsuccessful repetitions.

References

Talts, S., Betancourt, M., Simpson, D., Vehtari, A., & Gelman, A. (2018). Validating Bayesian inference algorithms with simulation-based calibration. arXiv. doi:10.48550/arXiv.1804.06788

See Also

posterior_bivariate(), draw_bivariate(), draw_agreement(), validate_bivariate

Examples

prior <- bivariate_prior(
  location = c(0, 0), kappa = 2,
  shape = 3, covariance = diag(2)
)

result <- sbc_bivariate(
  N = 4, model = "M3", prior = prior,
  contrast = "discrepancy",
  R = 5, n_draws = 50, bins = 5, seed = 123
)

result$histograms


Calibrate a bivariate simulation scenario from observed data

Description

Constructs a parametric plug-in data-generating mechanism from the observed paired change scores in a fitted bivariate model.

Usage

scenario_from_fit(
  fit,
  N = fit$N,
  ridge = 0,
  distribution = "normal",
  df = NULL,
  shift = 0,
  slope = 0,
  noise_sd = 0
)

Arguments

fit

An object of class babebi_bivariate returned by fit_bivariate().

N

Integer number of subjects in each simulated dataset. Defaults to the observed sample size.

ridge

Non-negative finite scalar added to the diagonal of the observed sample covariance matrix. Default is zero.

distribution

Distributional family passed to bivariate_scenario.

df

Student degrees of freedom, if applicable.

shift

Additive second-rater perturbation.

slope

Magnitude-dependent second-rater perturbation.

noise_sd

Standard deviation of the additional stochastic perturbation.

Details

Calibration uses the observed mean change parameters and the unrestricted sample covariance matrix with denominator N - 1.

The sample covariance is used independently of the covariance structure selected when fitting the model.

A positive ridge can be explicitly specified when the sample covariance is singular or requires regularisation.

Numerical singularity is assessed after diagonal regularisation using the reciprocal condition number of the rescaled covariance matrix.

No regularisation is introduced by default.

The fitted maximum likelihood covariance estimate need not be available.

The calibrated parameters are treated as fixed generative values. Sampling uncertainty in the calibration estimates is not propagated by this procedure.

Empirical calibration should be complemented by theoretically motivated sensitivity scenarios.

Value

An object of class babebi_scenario, with empirical provenance and calibration information.

See Also

fit_bivariate(), bivariate_scenario


Obtain the effective generative parameters of a simulation scenario

Description

Calculates the true population value and variance of a linear change-score contrast and the true distributional quantities governing agreement between the two raters.

Usage

scenario_truth(
  scenario,
  contrast,
  weight = NULL,
  content = 0.95,
  margin = NULL
)

Arguments

scenario

An object of class babebi_scenario.

contrast

Contrast name or numeric coefficient vector as specified in contrast_bivariate().

weight

Optional second-rater weight for a weighted contrast.

content

Probability content of the population agreement limits. Default is 0.95.

margin

Optional strictly positive finite practical agreement margin.

Details

All generative quantities refer to the effective distribution after applying the scenario perturbations.

The contrast coefficients refer to beta and gamma. Their equivalent coefficients for the two rater-specific changes are (c_beta - c_gamma, c_gamma).

Population agreement limits are the exact marginal quantiles of the individual discrepancy under the selected generative distribution.

Under the Student mechanism, these limits are calculated using Student quantiles and the appropriate scale parameter.

The practical agreement probability is the population probability that the absolute individual discrepancy does not exceed margin.

Value

A named list containing the contrast specification, coefficients, true contrast value, true variance of the individual contrast, true mean and variance of the individual discrepancy, population agreement limits, practical margin, and true practical agreement probability.

See Also

bivariate_scenario, validate_bivariate


Evaluate sensitivity of Bayesian evidence to prior specifications

Description

Recomputes Bayesian evidence for a single fitted covariance structure under a set of explicitly supplied proper conjugate priors.

Usage

sensitivity_bivariate(fit, priors, contrast = NULL, ...)

Arguments

fit

An object of class babebi_bivariate returned by fit_bivariate().

priors

Named list of at least two objects of class babebi_prior returned by bivariate_prior(). Names must be unique and non-empty.

contrast

Optional contrast specification. When NULL, only marginal likelihood sensitivity is evaluated.

...

Additional arguments passed to bayesfactor_bivariate when a contrast is supplied.

Details

The same fitted model and observed sufficient statistics are retained across prior specifications.

Each proper prior is used to update the same fitted model through posterior_bivariate().

The function reports the log marginal likelihood for every prior specification, together with its difference from the first specification.

These differences are sensitivity summaries. They should not automatically be interpreted as evidence for one substantive scientific hypothesis against another.

If contrast is supplied, the corresponding hypothesis comparison is evaluated separately under every prior.

No prior specifications are generated automatically. Sensitivity scenarios must be selected and justified by the researcher.

For sensitivity of comparisons between distinct covariance structures, repeat compare_bivariate under alternative sets of model-specific priors.

Value

A data frame with one row per prior specification. The columns scenario, log_marginal, and log_marginal_difference identify the prior specification, its log marginal likelihood, and its difference from the first scenario.

When a contrast is supplied, the additional columns log_bf10, log_bf01, bf10, bf01, prior_probability, and posterior_probability report the corresponding hypothesis comparison.

The original prior specifications are retained in the priors attribute.

See Also

bivariate_prior(), posterior_bivariate(), bayesfactor_bivariate, compare_bivariate

Examples

dat <- data.frame(
  id = rep(1:4, each = 4),
  time = rep(c("pre", "pre", "post", "post"), 4),
  rater = rep(c("r1", "r2"), 8),
  y = c(0, 0, 1, 2,
        0, 0, 2, 4,
        0, 0, 3, 1,
        0, 0, 4, 5)
)

fit <- fit_bivariate(
  dat, id, time, rater, y,
  model = "M3",
  time_order = c("pre", "post"),
  rater_order = c("r1", "r2")
)

priors <- list(
  lower_precision = bivariate_prior(
    c(0, 0), kappa = 0.5, shape = 3,
    covariance = diag(c(2, 2))
  ),
  higher_precision = bivariate_prior(
    c(0, 0), kappa = 4, shape = 3,
    covariance = diag(c(2, 2))
  )
)

sensitivity_bivariate(
  fit,
  priors,
  contrast = "average",
  hypothesis = "point",
  null = 0
)


Simulate paired bivariate change scores

Description

Generates an independent sample of paired change scores from a theoretical or empirically calibrated simulation scenario.

Usage

simulate_bivariate(scenario, seed = NULL, format = "changes")

Arguments

scenario

An object of class babebi_scenario.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

format

Output format, either "changes" or "long". Default is "changes".

Details

Gaussian draws are generated by right multiplication of a matrix of independent standard normal draws by the upper triangular Cholesky factor of the effective covariance.

Under the Student mechanism, each Gaussian row is multiplied by an independent radial factor involving a chi-squared random variable. The resulting population covariance equals the effective covariance specified in the scenario.

The long-format representation contains zero baseline scores and simulated follow-up scores equal to the generated changes.

This representation preserves the paired change scores for analysis with the package functions. It does not constitute a generative model for baseline or follow-up measurements separately.

Value

A numeric matrix with N rows and two columns named r1 and r2, or a long-format data frame with columns id, time, rater, and y.

See Also

bivariate_scenario, validate_bivariate

Examples

scenario <- bivariate_scenario(
  N = 6, beta = 0.5, gamma = 0.2,
  covariance = diag(2)
)

simulate_bivariate(scenario, seed = 123)
simulate_bivariate(scenario, seed = 123, format = "long")


Generate paired pre-post ordinal observations

Description

Generates complete repeated-measures ordinal data from the hierarchical cumulative probit mechanism.

Usage

simulate_ordinal(
  N,
  coefficients,
  random_covariance,
  cutpoints,
  category_order,
  seed = NULL
)

Arguments

N

Integer number of subjects, at least two.

coefficients

Finite numeric vector of alpha, delta, beta, and gamma, in this order.

random_covariance

Symmetric positive-definite 2 by 2 covariance of the subject-specific occasion effects.

cutpoints

Strictly increasing finite numeric vector of cutpoints, with first element equal to zero.

category_order

Explicit ordered vector of category labels.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

Details

Subject-specific occasion effects are independently generated from a bivariate Gaussian distribution.

Conditional residuals are independently generated standard Gaussian variables. Observed categories are obtained by discretising the latent responses using the common cutpoints.

Unlike the continuous change-score simulation engine, this function generates baseline and follow-up responses separately.

Value

A long-format data frame with columns id, time, rater, and y. The outcome is an ordered factor.

See Also

fit_ordinal(), validate_ordinal()

Examples

simulate_ordinal(
  N = 6, coefficients = c(0, 0, 0.5, 0.2),
  random_covariance = diag(2),
  cutpoints = c(0, 1),
  category_order = c("low", "medium", "high"),
  seed = 123
)


Summarise performance in a bivariate simulation study

Description

Calculates empirical performance measures and Monte Carlo standard errors from the repetition-level results of a bivariate simulation study.

Usage

summarise_validation(object)

Arguments

object

An object of class babebi_simulation returned by validate_bivariate.

Details

Performance is summarised separately for each method.

The estimand bias is the mean estimation error. The mean squared error is the mean squared estimation error. The root mean squared error is the square root of this quantity.

Coverage is the proportion of available intervals containing the effective generative value. Interval width is averaged over the available intervals.

Interval exclusion is the proportion of available intervals excluding the specified null value. Its interpretation depends on the data-generating scenario and the inferential method.

Posterior positive probabilities are evaluated against the fixed generative event that the contrast is positive. Such summaries do not establish prior-predictive Bayesian calibration.

Log Bayes factors and log marginal likelihoods are summarised on their logarithmic scales.

Agreement performance includes errors in estimated discrepancy variance and population limits of agreement, predictive interval coverage, probability estimation error, and the Brier score for practical agreement of an independent future subject.

Each performance measure uses the repetitions for which its required quantities are available. The number of usable repetitions is reported alongside the total number requested.

Failure rates are calculated separately for estimation, point evidence, marginal likelihood, and agreement.

Inapplicable and unrequested stages are excluded from the denominators of the corresponding failure rates.

A stage blocked by an earlier computational failure is counted as unavailable in the stage-specific failure rate.

Monte Carlo standard errors of means are estimated using the empirical standard deviation divided by the square root of the number of usable repetitions.

Proportion standard errors use the empirical Bernoulli variance. Zero estimated standard errors for proportions at zero or one do not establish that the underlying probabilities equal those boundaries.

Root mean squared error and empirical standard deviation standard errors use first-order delta-method approximations.

Monte Carlo standard errors are unavailable with fewer than two usable repetitions.

Under Student data-generating mechanisms with degrees of freedom not exceeding four, standard errors of squared estimation errors and empirical standard deviations are conservatively omitted.

For errors in the estimated discrepancy variance, stronger moment requirements are applied to quadratic performance measures. These restrictions are conservative safeguards, not general proofs of the existence of every remaining performance-measure variance.

All performance measures conditional on successful analysis must be interpreted jointly with computational failure rates.

Value

A data frame with columns:

method

Analysis method name.

metric

Performance measure.

estimate

Estimated performance.

mcse

Estimated Monte Carlo standard error.

n_used

Number of usable repetitions.

n_total

Total number of requested repetitions.

mcse_method

Method used for the Monte Carlo standard error, or the reason it was not calculated.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074-2102. doi:10.1002/sim.8086

See Also

validate_bivariate, compare_validation


Summarise a babebi fit object

Description

Summarise a babebi fit object

Usage

## S3 method for class 'babebi_fit'
summary(object, digits = 3, ...)

Arguments

object

An object of class babebi_fit.

digits

Number of digits to print.

...

Further arguments passed to or from other methods.

Value

An object of class summary.babebi_fit.


Evaluate inferential performance in a bivariate simulation scenario

Description

Compares inferential methods using the same independently generated datasets under a fixed data-generating mechanism.

Usage

validate_bivariate(
  scenario,
  methods,
  contrast,
  R = 1000L,
  weight = NULL,
  level = 0.95,
  null = 0,
  evidence = FALSE,
  bf_threshold = NULL,
  prob_threshold = NULL,
  agreement = FALSE,
  margin = NULL,
  min_coverage = NULL,
  content = 0.95,
  n_draws = 4000L,
  seed = NULL,
  keep_data = FALSE,
  rel_tol = 1e-08,
  abs_tol = 1e-10,
  subdivisions = 1000L
)

Arguments

scenario

An object of class babebi_scenario.

methods

Uniquely named list of method specifications. Each element must be "legacy", "paired_t", or a list containing model and prior. Bayesian model specifications use M0, M1, M2, or M3, and either "reference" or a proper prior returned by bivariate_prior().

contrast

Contrast name or numeric coefficient vector as specified in contrast_bivariate().

R

Number of independent simulation repetitions. An integer of at least two. Default is 1000.

weight

Optional second-rater weight.

level

Probability content of the interval for the population contrast. Default is 0.95.

null

Finite scalar defining the point hypothesis and the null value used to evaluate interval exclusion. Default is zero.

evidence

Logical scalar indicating whether marginal likelihoods and point Bayes factors should be evaluated. Default is FALSE.

bf_threshold

Optional finite Bayes factor threshold greater than one. Requires evidence = TRUE.

prob_threshold

Optional probability threshold strictly between zero and one for posterior positive-contrast decisions.

agreement

Logical scalar indicating whether the agreement analysis should be performed for the new Bayesian methods. Default is FALSE.

margin

Optional strictly positive practical agreement margin. Requires agreement = TRUE.

min_coverage

Optional minimum acceptable population coverage, strictly between zero and one. Requires margin.

content

Probability content of population agreement limits and predictive discrepancy intervals. Default is 0.95.

n_draws

Number of posterior draws used by the legacy approximation and the agreement analysis. An integer of at least 1000. Default is 4000.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

keep_data

Logical scalar indicating whether the simulated datasets and independent future observations are retained. Default is FALSE.

rel_tol

Relative integration tolerance passed to the contrast and evidence procedures.

abs_tol

Absolute integration tolerance passed to the contrast and agreement procedures.

subdivisions

Maximum number of subdivisions for adaptive numerical integration.

Details

The simulation separates the data-generating mechanism from the model used for inference. All methods analyse the same generated subjects within a repetition.

The legacy method calls the original fit_model() function. Its point estimate is the linear contrast of the original least-squares estimates. Its interval and posterior positive probability are calculated from the original approximate posterior draws.

For the reference-rater contrast at the 95 percent level, these summaries reproduce the corresponding procedure of the original fitted object.

For other contrasts, the original joint approximate posterior is transformed linearly.

The original BIC-based Bayes factor is available only for the reference-rater contrast with a zero point null. Its logarithm is calculated directly from the difference between the original BIC expressions, preserving the original residual sum-of-squares floor. This avoids overflow on the ordinary Bayes factor scale.

The paired Student benchmark analyses the subject-level linear contrast using its sample mean and the conventional Student interval with N - 1 degrees of freedom. This is a frequentist confidence interval.

The new Bayesian methods use fit_bivariate(), posterior_bivariate(), and contrast_bivariate(). Their point estimates are posterior medians.

Improper reference priors are allowed for posterior inference but not for marginal likelihoods or ordinary Bayes factors.

Proper Bayesian model specifications may use different priors within the same covariance structure to evaluate sensitivity.

Marginal likelihoods and point Bayes factors are evaluated as separate inferential stages. Their failure does not remove otherwise valid parameter estimates.

Agreement analysis uses agreement_bivariate() and is evaluated separately from estimation and evidence.

Each repetition contains an independently generated future subject for predictive performance evaluation.

All datasets and future observations are generated before any method is fitted. This prevents the number or ordering of analysis methods from changing the generated data.

A common analysis seed is assigned to the methods within each repetition. This also makes seeded stochastic analyses invariant to the order of the supplied methods.

These analysis seeds are generated independently of the method specifications. All pseudo-random results remain conditional on the random-number generator implementation.

Errors and warnings are recorded for individual repetitions and inferential stages. Failed analyses remain in the returned repetition-level results.

A fatal failure to generate finite data stops the simulation. Generated samples are not silently replaced.

Simulation performance at fixed population parameters does not establish prior-predictive Bayesian calibration.

Value

A named list of class babebi_simulation containing:

scenario

The data-generating scenario.

truth

Effective generative quantities.

methods

Validated analysis method specifications.

settings

Simulation and inference settings.

replicates

A data frame with one row per method and repetition, including the true parameter, estimate, interval, posterior probabilities, log evidence, agreement summaries, independent future discrepancy, stage-specific statuses, and diagnostic messages.

datasets

Generated data, including the future observation as the final row, if requested.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074-2102. doi:10.1002/sim.8086

See Also

summarise_validation, compare_validation, sbc_bivariate

Examples

scenario <- bivariate_scenario(
  N = 6, beta = 0.5, gamma = 0.2,
  covariance = diag(2)
)

methods <- list(
  original = "legacy",
  classical = "paired_t",
  reference_M0 = list(model = "M0", prior = "reference")
)

result <- validate_bivariate(
  scenario, methods, contrast = "reference",
  R = 5, n_draws = 1000, seed = 123
)

summarise_validation(result)


Validate ordinal inference under fixed generative parameters

Description

Simulates independent ordinal datasets, fits the hierarchical ordinal model, and evaluates a selected latent mean contrast.

Usage

validate_ordinal(
  N,
  coefficients,
  random_covariance,
  cutpoints,
  category_order,
  prior,
  contrast,
  R,
  weight = NULL,
  level = 0.95,
  chains = 4L,
  warmup = 1000L,
  draws = 2000L,
  rhat_limit = 1.01,
  ess_min = 400,
  seed = NULL
)

Arguments

N

Integer number of subjects per dataset, at least two.

coefficients

Generative alpha, delta, beta, and gamma.

random_covariance

Generative occasion-effect covariance.

cutpoints

Generative cutpoints, starting at zero.

category_order

Ordered vector of category labels.

prior

Proper analysis prior returned by ordinal_prior().

contrast

Contrast name or numeric coefficient vector as specified in contrast_bivariate().

R

Number of independent repetitions, at least two.

weight

Optional second-rater weight.

level

Credible interval probability content. Default is 0.95.

chains

Number of MCMC chains per analysis.

warmup

Number of discarded iterations per chain.

draws

Number of retained iterations per chain.

rhat_limit

Diagnostic R-hat threshold.

ess_min

Minimum bulk and tail effective sample sizes.

seed

Optional non-negative integer random seed. When supplied, the previous .Random.seed is restored on exit, including its original absence. This function supports standard R random-number generators, excluding Box-Muller, user-supplied generators and Buggy Kinderman-Ramage. Unsupported configurations are rejected, including when seed is NULL.

Details

All datasets are generated before fitting any model. The generative parameters and analysis prior are specified separately. The function does not construct an analysis prior from the true generative parameters.

Posterior medians are used as point estimates. Bias, mean squared error, root mean squared error, coverage and interval width are reported with Monte Carlo standard errors across repetitions.

Sampling failures and diagnostic inadequacy are recorded separately.

Successful analyses with inadequate diagnostics are retained in the primary performance summary. A secondary summary uses only analyses satisfying all specified diagnostics.

Both summaries must be interpreted with the failure and diagnostic frequencies. Selection on diagnostic adequacy can change the population of simulated datasets being analysed.

This is a fixed-parameter simulation study, not simulation-based calibration of autocorrelated MCMC ranks.

Value

A list of class babebi_ordinal_validation containing the scenario and sampling settings, true contrast value, repetition-level results, primary performance summary, diagnostic-adequate performance summary, and computational failure and diagnostic inadequacy summaries.

See Also

simulate_ordinal(), fit_ordinal(), ordinal_diagnostics()