Language / 言語: English introduction | パッケージ紹介
BayesRTMB is an R package for writing and fitting statistical models with RTMB as the automatic differentiation engine.
You can start from wrapper functions such as rtmb_lm(),
rtmb_glmer(), rtmb_corr(), and
rtmb_ttest(), or write your own model with
rtmb_code(). The same model object can then be used for
MCMC, MAP estimation, variational inference, and frequency-oriented
classical analyses where supported.
setup, parameters, transform,
model, and generate blocks.$sample(), $optimize(),
$variational(), and $classic() from a common
model object.$classic() for frequency-oriented outputs, including
AIC(), BIC(), and anova() for
supported fits.random = TRUE and use RTMB’s Laplace
machinery for latent variables and mixed models.You can install BayesRTMB from CRAN.
install.packages("BayesRTMB")The development version can be installed from GitHub with either
pak or remotes.
pak::pak("norimune/BayesRTMB")remotes::install_github("norimune/BayesRTMB")For ordinary use, Windows users can install the CRAN binary package without Rtools. Rtools is only needed for source installation, development, or compiling custom TMB C++ templates.
pkgbuild::check_build_tools(debug = TRUE)If you install BayesRTMB from source and this check fails, install the Rtools version that matches your R version from the Rtools page, restart R, and try again.
For standard analyses, start with a wrapper function.
library(BayesRTMB)
data(debate)
mdl <- rtmb_lm(sat ~ talk * perf, data = debate)
fit_mcmc <- mdl$sample()
fit_map <- mdl$optimize()
fit_lm <- mdl$classic()You can also write a model directly.
Y <- debate$sat
X <- debate[c("talk","perf")] |> as.matrix()
data_list <- list(Y = Y, X = X)
code <- rtmb_code(
setup = {
N <- length(Y)
K <- ncol(X)
},
parameters = {
Intercept <- Dim(1)
b <- Dim(K)
sigma = Dim(lower = 0)
},
model = {
mu <- Intercept + X %*% b
Y ~ normal(mu, sigma)
Intercept ~ normal(0, 10)
b ~ normal(0, 10)
sigma ~ exponential(1)
}
)
mdl_custom <- rtmb_model(data_list, code)
fit_custom <- mdl_custom$sample()rtmb_glmer() for
mixed models, GLMMs, priors, residual correlation, and
visualization.rtmb_code().