Build a brms Custom Family + Stanvars Pair from a Single Spec
Source:R/stan-helpers.R
build_brms_custom_family.RdConvenience function that combines custom_family and
stanvar into the standard list(custom_family,
stanvars_family) pair returned by every brms_custom_* helper in
hbsaems. The Stan code is read directly from
inst/stan/<name>.stan – the user does not need to maintain it as
an R string.
Usage
build_brms_custom_family(
name,
dpars,
links,
lb = NA,
ub = NA,
type = c("real", "int"),
loop = FALSE,
log_lik = NULL,
posterior_predict = NULL,
posterior_epred = NULL,
use_stan_native = FALSE
)Arguments
- name
Character. Family name; must match a
<name>.stanfile underinst/stan/.- dpars
Character vector of distributional parameter names. The first MUST be
"mu"(brms convention).- links
Character vector of link functions, same length as
dpars. Common values:"identity","log","logit".- lb, ub
Numeric vectors of lower / upper bounds;
NAfor none.- type
"real"(continuous) or"int"(discrete).- loop
Logical.
FALSE(default) selects the vectorised brms convention (Stan signatures take vectors ofyandmu);TRUEselects scalar Stan signatures. The default matches the neodistr convention. Whichever you choose, the corresponding.stanfile underinst/stan/must use the same convention.- log_lik
Optional function for computing observation-level log-likelihoods (used by
loo(),waic()). Signature must befunction(i, prep). See the brms vignette "Define Custom Response Distributions" for details.- posterior_predict
Optional function for drawing from the posterior predictive distribution (used by
pp_check(),posterior_predict()). Signaturefunction(i, prep, ...).- posterior_epred
Optional function returning the conditional expectation \(E[Y \mid X]\) (used by
fitted(),conditional_effects()). Signaturefunction(prep).- use_stan_native
Logical. If
TRUE, nostanvarsblock is attached – the<name>_lpdffunction is assumed to exist as a Stan built-in (e.g.\loglogistic_lpdfin Stan \(\geq\) 2.29). WhenFALSE(the default), the function definition is loaded frominst/stan/<name>.stan.
Value
A list with two elements:
custom_familyA
brms::customfamilyobject.stanvars_familyA
brms::stanvarsobject with the Stan code in thefunctionsblock, orNULLwhenuse_stan_native = TRUE.
Details
Stan code is built once per call; if your code is reused many times, wrap the returned object in a function and call it lazily.
Examples
# \donttest{
library(hbsaems)
library(brms)
# Build the loglogistic family. Stan code is loaded from
# inst/stan/hbsae_loglogistic.stan — the `hbsae_` prefix avoids
# collision with Stan's BUILT-IN `loglogistic_lpdf` (Stan >= 2.29).
ll <- build_brms_custom_family(
name = "hbsae_loglogistic",
dpars = c("mu", "beta"),
links = c("log", "log"),
lb = c(0, 0),
ub = c(NA, NA),
type = "real"
)
class(ll$custom_family)
#> [1] "customfamily" "brmsfamily" "family"
# }