| Title: | Bayesian Regression Modeling Strategies |
|---|---|
| Description: | A Bayesian companion to the 'rms' package, 'rmsb' provides Bayesian model fitting, post-fit estimation, and graphics. It implements Bayesian regression models whose fit objects can be processed by 'rms' functions such as 'contrast()', 'summary()', 'Predict()', 'nomogram()', and 'latex()'. The fitting function currently implemented in the package is 'blrm()' for Bayesian logistic binary and ordinal regression with optional clustering, censoring, and departures from the proportional odds assumption using the partial proportional odds model of Peterson and Harrell (1990) <https://www.jstor.org/stable/2347760>. |
| Authors: | Frank Harrell [aut, cre] (ORCID: <https://orcid.org/0000-0002-8271-5493>), Ben Goodrich [ctb] (contributed Stan code), Ben Bolker [ctb] (wrote original code that is folded into the pdensityContour function), Doug Bates [ctb] (write original code for highest posterior density interval that is folded into the HPDint function) |
| Maintainer: | Frank Harrell <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.1-3 |
| Built: | 2026-07-10 21:36:38 UTC |
| Source: | https://github.com/harrelfe/rmsb |
Regression Modeling Strategies Bayesian
The rmsb package is an appendage to the rms package that
implements Bayesian regression models whose fit objects can be processed
by rms functions such as contrast, summary, Predict, nomogram,
and latex. The fitting function
currently implemented in the package is blrm for Bayesian logistic
binary and ordinal regression with optional clustering, censoring, and
departures from the proportional odds assumption using the partial
proportional odds model of Peterson and Harrell (1990).
Stan Development Team (2020). RStan: the R interface to Stan. R package version 2.19.3. https://mc-stan.org
https://hbiostat.org/R/rmsb/ for the package's main web page
https://hbiostat.org/R/examples/blrm/blrm.html for a vignette with
many examples of using the blrm function
Uses rstan with pre-compiled Stan code, or cmdstan to get posterior draws of parameters from a binary logistic or proportional odds semiparametric ordinal logistic model. The Stan code internally using the qr decompositon on the design matrix so that highly collinear columns of the matrix do not hinder the posterior sampling. The parameters are transformed back to the original scale before returning results to R. Design matrix columns are centered before running Stan, so Stan diagnostic output will have the intercept terms shifted but the results of blrm() for intercepts are for the original uncentered data. The only prior distributions for regression betas are normal with mean zero. Priors are specified on contrasts so that they can be specified on a meaningful scale and so that more complex patterns can be imposed. Parameters that are not involved in any contrasts in pcontrast or npcontrast have non-informative priors. Contrasts are automatically converted to the QR space used in Stan code.
blrm( formula, ppo = NULL, cppo = NULL, data = environment(formula), subset, na.action = na.delete, priorsdppo = rep(100, pppo), iprior = 0, conc = 1/(0.8 + 0.35 * max(k, 3)), ascale = 1, psigma = 1, rsdmean = if (psigma == 1) 0 else 1, rsdsd = 1, normcppo = FALSE, pcontrast = NULL, npcontrast = NULL, backend = c("rstan", "cmdstan"), iter = 2000, warmup = iter/2, chains = 4, refresh = 0, progress = if (refresh > 0) "stan-progress.txt" else "", x = TRUE, y = TRUE, loo = n <= 1000, ppairs = NULL, method = c("both", "sampling", "optimizing"), inito = if (length(ppo)) 0 else "random", inits = inito, standata = FALSE, file = NULL, debug = FALSE, sampling.args = NULL, showopt = FALSE, ... )blrm( formula, ppo = NULL, cppo = NULL, data = environment(formula), subset, na.action = na.delete, priorsdppo = rep(100, pppo), iprior = 0, conc = 1/(0.8 + 0.35 * max(k, 3)), ascale = 1, psigma = 1, rsdmean = if (psigma == 1) 0 else 1, rsdsd = 1, normcppo = FALSE, pcontrast = NULL, npcontrast = NULL, backend = c("rstan", "cmdstan"), iter = 2000, warmup = iter/2, chains = 4, refresh = 0, progress = if (refresh > 0) "stan-progress.txt" else "", x = TRUE, y = TRUE, loo = n <= 1000, ppairs = NULL, method = c("both", "sampling", "optimizing"), inito = if (length(ppo)) 0 else "random", inits = inito, standata = FALSE, file = NULL, debug = FALSE, sampling.args = NULL, showopt = FALSE, ... )
formula |
a R formula object that can use |
ppo |
formula specifying the model predictors for which proportional odds is not assumed |
cppo |
a function that if present causes a constrained partial PO model to be fit. The function specifies the values in the Gamma vector in Peterson and Harrell (1990) equation (6). Sometimes to make posterior sampling better behaved, the function should be scaled and centered. This is done by wrapping |
data |
a data frame; defaults to using objects from the calling environment |
subset |
a logical vector or integer subscript vector specifying which subset of data whould be used |
na.action |
default is |
priorsdppo |
vector of prior standard deviations for non-proportional odds parameters. The last element is the only one for which the SD corresponds to the original data scale. This only applies to the unconstrained PPO model. |
iprior |
specifies whether to use a Dirichlet distribution for the cell probabilities, which induce a more complex prior distribution for the intercepts ( |
conc |
the Dirichlet distribution concentration parameter for the prior distribution of cell probabilities at covariate means. The default is the reciprocal of 0.8 + 0.35 max(k, 3) where k is the number of Y categories. The default is chosen to make the posterior mean of the intercepts more closely match the MLE. For optimizing, the concentration parameter is always 1.0 when |
ascale |
scale parameter for the t-distribution for priors for the intercepts if |
psigma |
defaults to 1 for a half-t distribution with 4 d.f., location parameter |
rsdmean |
the assumed mean of the prior distribution of the standard deviation of random effects. When |
rsdsd |
applies only to |
normcppo |
set to |
pcontrast |
a list specifying contrasts that are to be given Gaussian prior distributions. The predictor combinations specified in |
npcontrast |
like |
backend |
set to |
iter |
number of posterior samples per chain for |
warmup |
number of warmup iterations to discard. Default is |
chains |
number of separate chains to run |
refresh |
see |
progress |
see |
x |
set to |
y |
set to |
loo |
set to |
ppairs |
set to a file name to run |
method |
set to |
inito |
intial value for optimization. The default is the |
inits |
initial value for sampling, defaults to |
standata |
set to |
file |
a file name for a |
debug |
set to |
sampling.args |
a list containing parameters to pass to |
showopt |
set to |
... |
passed to |
The partial proportional odds model of Peterson and Harrell (1990) is implemented, and is invoked when the user specifies a second model formula as the ppo argument. This formula has no left-hand-side variable, and has right-side variables that are a subset of those in formula specifying for which predictors the proportional odds assumption is relaxed.
The Peterson and Harrell (1990) constrained partial proportional odds is also implemented, and is usually preferred to the above unconstrained PPO model as it adds a vector of coefficients instead of a matrix of coefficients. In the constrained PPO model the user provides a function cppo that computes a score for all observed values of the dependent variable. For example with a discrete ordinal outcome cppo may return a value of 1.0 for a specific value of Y and zero otherwise. That will result in a departure from the proportional odds assumption for just that one level of Y. The value returned by cppo at the lowest Y value is never used in any case.
blrm() also handles single-level hierarchical random effects models for the case when there are repeated measurements per subject which are reflected as random intercepts, and a different experimental model that allows for AR(1) serial correlation within subject. For both setups, a cluster term in the model signals the existence of subject-specific random effects.
When using the cmdstan backend, cmdstanr will need to compile the Stan code once per computer, only recompiling the code when the Stan source code changes. By default the compiled code is stored in directory .rmsb under your home directory. Specify options(rmsbdir=) to specify a different location. You should specify rmsbdir to be in a project-specific location if you want to archive code for old projects.
If you want to run MCMC sampling even when no inputs or Stan code have changed, i.e., to use a different random number seed for the sampling process when you did not specify sampling.args(seed=...), remove the file before running blrm.
Set options(rmsbmsg=FALSE) to suppress certain information messages.
See here and here for multiple examples with results.
an rms fit object of class blrm, rmsb, rms that also contains rstan or cmdstanr results under the name rstan. In the rstan results, which are also used to produce diagnostics, the intercepts are shifted because of the centering of columns of the design matrix done by blrm(). With method='optimizing' a class-less list is return with these elements: coefficients (MLEs), beta (non-intercept parameters on the QR decomposition scale), deviance (-2 log likelihood), return_code (see rstan::optimizing()), and, if you specified hessian=TRUE to blrm(), the Hessian matrix. To learn about the scaling of orthogonalized QR design matrix columns, look at the xqrsd object in the returned object. This is the vector of SDs for all the columns of the transformed matrix. The returned element sampling_time is the elapsed time for running posterior samplers, in seconds. This will be just a little more than the time for running one CPU core for one chain.
Frank Harrell and Ben Goodrich
print.blrm(), blrmStats(), stanDx(), stanGet(), coef.rmsb(), vcov.rmsb(), print.rmsb(), coef.rmsb()
## Not run: getHdata(titanic3) dd <- datadist(titanic3); options(datadist='dd') f <- blrm(survived ~ (rcs(age, 5) + sex + pclass)^2, data=titanic3) f # model summary using print.blrm coef(f) # compute posterior mean parameter values coef(f, 'median') # compute posterior median values stanDx(f) # print basic Stan diagnostics s <- stanGet(f) # extract rstan object from fit plot(s, pars=f$betas) # Stan posteriors for beta parameters stanDxplot(s) # Stan diagnostic plots by chain blrmStats(f) # more details about predictive accuracy measures ggplot(Predict(...)) # standard rms output summary(f, ...) # invokes summary.rms contrast(f, ...) # contrast.rms computes HPD intervals plot(nomogram(f, ...)) # plot nomogram using posterior mean parameters # Fit a random effects model to handle multiple observations per # subject ID using cmdstan # options(rmsb.backend='cmdstan') f <- blrm(outcome ~ rcs(age, 5) + sex + cluster(id), data=mydata) ## End(Not run)## Not run: getHdata(titanic3) dd <- datadist(titanic3); options(datadist='dd') f <- blrm(survived ~ (rcs(age, 5) + sex + pclass)^2, data=titanic3) f # model summary using print.blrm coef(f) # compute posterior mean parameter values coef(f, 'median') # compute posterior median values stanDx(f) # print basic Stan diagnostics s <- stanGet(f) # extract rstan object from fit plot(s, pars=f$betas) # Stan posteriors for beta parameters stanDxplot(s) # Stan diagnostic plots by chain blrmStats(f) # more details about predictive accuracy measures ggplot(Predict(...)) # standard rms output summary(f, ...) # invokes summary.rms contrast(f, ...) # contrast.rms computes HPD intervals plot(nomogram(f, ...)) # plot nomogram using posterior mean parameters # Fit a random effects model to handle multiple observations per # subject ID using cmdstan # options(rmsb.backend='cmdstan') f <- blrm(outcome ~ rcs(age, 5) + sex + cluster(id), data=mydata) ## End(Not run)
For a binary or ordinal logistic regression fit from blrm(), computes several indexes of predictive accuracy along with highest posterior density intervals for them. Optionally plots their posterior densities.
When there are more than two levels of the outcome variable, computes Somers' Dxy and c-index on a random sample of 10,000 observations.
blrmStats(fit, ns = 400, prob = 0.95, pl = FALSE, dist = c("density", "hist"))blrmStats(fit, ns = 400, prob = 0.95, pl = FALSE, dist = c("density", "hist"))
fit |
an object produced by |
ns |
number of posterior draws to use in the calculations (default is 400) |
prob |
HPD interval probability (default is 0.95) |
pl |
set to |
dist |
if |
list of class blrmStats whose most important element is Stats. The indexes computed are defined below, with gp, B, EV, and vp computed using the intercept corresponding to the median value of Y. See https://fharrell.com/post/addvalue for more information.
Somers' Dxy rank correlation between predicted and observed. The concordance probability (c-index; AUROC in the binary Y case) may be obtained from the relationship Dxy=2(c-0.5).
Gini's mean difference: the average absolute difference over all pairs of linear predictor values
Gini's mean difference on the predicted probability scale
Brier score
explained variation
variance of linear predictor
variable of estimated probabilities
Frank Harrell
## Not run: f <- blrm(...) blrmStats(f, pl=TRUE) # print and plot ## End(Not run)## Not run: f <- blrm(...) blrmStats(f, pl=TRUE) # print and plot ## End(Not run)
Cluster Function for Random Effects
cluster(x)cluster(x)
x |
a vector representing a categorical vector |
Used by blrm to signal a categorical variable to generate random effects.
x unchanged
Frank Harrell
Computes either the posterior mean (default), posterior median, or posterior mode of the parameters in an rms Bayesian regression model
## S3 method for class 'rmsb' coef(object, stat = c("mean", "median", "mode"), ...)## S3 method for class 'rmsb' coef(object, stat = c("mean", "median", "mode"), ...)
object |
an object created by an |
stat |
name of measure of posterior distribution central tendency to compute |
... |
ignored |
a vector of intercepts and regression coefficients
Frank Harrell
## Not run: f <- blrm(...) coef(f, stat='mode') ## End(Not run)## Not run: f <- blrm(...) coef(f, stat='mode') ## End(Not run)
Uses loo::loo_model_weights() to compare a series of models such as those created with blrm()
compareBmods(..., method = "stacking", r_eff_list = NULL)compareBmods(..., method = "stacking", r_eff_list = NULL)
... |
a series of model fits |
method |
|
r_eff_list |
a loo::loo_model_weights() object
Frank Harrell
From a sample from a distribution computes a symmetry measure. By default it is the gap between the mean and the 0.95 quantile divided by the gap between the 0.05 quantile and the mean.
distSym(x, prob = 0.9, na.rm = FALSE)distSym(x, prob = 0.9, na.rm = FALSE)
x |
a numeric vector representing a sample from a continuous distribution |
prob |
quantile interval coverage |
na.rm |
set to |
a scalar with a value of 1.0 indicating symmetry
Frank Harrell
blrm()
For a blrm() object generates a function for computing the estimates of the function Prob(Y>=y) given one or more values of the linear predictor using the reference (median) intercept. This function can optionally be evaluated at only a set of user-specified y values, otherwise a right-step function is returned. There is a plot method for plotting the step functions, and if more than one linear predictor was evaluated multiple step functions are drawn. ExProb is especially useful for nomogram(). The linear predictor argument is a posterior summarized linear predictor lp (e.g. using posterior mean of intercepts and slopes) computed at the reference intercept. lptau must be provided when call the created function if the model is a partial proportional odds model.
## S3 method for class 'blrm' ExProb(object, posterior.summary = c("mean", "median"), ...)## S3 method for class 'blrm' ExProb(object, posterior.summary = c("mean", "median"), ...)
object |
a |
posterior.summary |
defaults to posterior mean; may also specify |
... |
ignored |
an R function
Frank Harrell
Retrieves posterior mean, median, or mode (if available)
getParamCoef( fit, posterior.summary = c("mean", "median", "mode"), what = c("both", "betas", "taus") )getParamCoef( fit, posterior.summary = c("mean", "median", "mode"), what = c("both", "betas", "taus") )
fit |
a Bayesian model fit from |
posterior.summary |
which summary statistic (Bayesian point estimate) to fetch |
what |
specifies which coefficients to include. Default is all. Specify |
vector of regression coefficients
Frank Harrell
Adapts code from coda::HPDinterval() to compute a highest posterior density interval from posterior samples for a single parameter. Quoting from the coda help file, for each parameter the interval is constructed from the empirical cdf of the sample as the shortest interval for which the difference in the ecdf values of the endpoints is the nominal probability. Assuming that the distribution is not severely multimodal, this is the HPD interval.
HPDint(x, prob = 0.95)HPDint(x, prob = 0.95)
x |
a vector of posterior draws |
prob |
desired probability coverage |
a 2-vector with elements Lower and Upper
Douglas Bates and Frank Harrell
blrm()
Creates a function to turn a posterior summarized linear predictor lp (e.g. using posterior mean of intercepts and slopes) computed at the reference intercept into e.g. an estimate of mean Y using the posterior mean of all the intercept. lptau must be provided when call the created function if the model is a partial proportional odds model.
## S3 method for class 'blrm' Mean(object, codes = FALSE, posterior.summary = c("mean", "median"), ...)## S3 method for class 'blrm' Mean(object, codes = FALSE, posterior.summary = c("mean", "median"), ...)
object |
a |
codes |
if |
posterior.summary |
defaults to posterior mean; may also specify |
... |
ignored |
an R function
Frank Harrell
Computes coordinates of a highest density contour containing a given probability volume given a sample from a continuous bivariate distribution, and optionally plots. The default method assumes an elliptical shape, but one can optionally use a kernel density estimator.
Code adapted from embbook::HPDregionplot. See https://www.sumsar.net/blog/2014/11/how-to-summarize-a-2d-posterior-using-a-highest-density-ellipse/.
pdensityContour( x, y, method = c("ellipse", "kernel"), prob = 0.95, otherprob = c(0.01, 0.1, 0.25, 0.5, 0.75, 0.9), h = c(1.3 * MASS::bandwidth.nrd(x), 1.3 * MASS::bandwidth.nrd(y)), n = 70, pl = FALSE )pdensityContour( x, y, method = c("ellipse", "kernel"), prob = 0.95, otherprob = c(0.01, 0.1, 0.25, 0.5, 0.75, 0.9), h = c(1.3 * MASS::bandwidth.nrd(x), 1.3 * MASS::bandwidth.nrd(y)), n = 70, pl = FALSE )
x |
a numeric vector |
y |
a numeric vector the same length of x |
method |
defaults to |
prob |
main probability coverage (the only one for |
otherprob |
vector of other probability coverages for |
h |
vector of bandwidths for x and y. See |
n |
number of grid points in each direction, defaulting to normal reference bandwidth (see |
pl |
set to |
a 2-column matrix with x and y coordinates unless pl=TRUE in which case a ggplot2 graphic is returned
Ben Bolker and Frank Harrell
PostF
Computes highest posterior density and posterior mean and median as vertical lines, and plots these on the density function. You can transform the posterior draws while plotting.
## S3 method for class 'PostF' plot( x, ..., cint = 0.95, label = NULL, type = c("linetype", "facet"), ltitle = "" )## S3 method for class 'PostF' plot( x, ..., cint = 0.95, label = NULL, type = c("linetype", "facet"), ltitle = "" )
x |
result of running a function created by |
... |
other results created by such functions |
cint |
interval probability |
label |
x-axis label if not the expression originally evaluated. When more than one result is plotted, |
type |
when plotting more than one result specifies whether to make one plot distinguishing results by line type, or whether to make separate panels |
ltitle |
used of |
ggplot2 object
Frank Harrell
For an rms Bayesian fit object, plots posterior densities for selected parameters along with posterior mode, mean, median, and highest posterior density interval. If the fit was produced by stackMI the density represents the distribution after stacking the posterior draws over imputations, and the per-imputation density is also drawn as pale curves. If exactly two parameters are being plotted and bivar=TRUE, hightest bivariate posterior density contrours are plotted instead, for a variety of prob values including the one specified, using
## S3 method for class 'rmsb' plot( x, which = NULL, nrow = NULL, ncol = NULL, prob = 0.95, bivar = FALSE, bivarmethod = c("ellipse", "kernel"), ... )## S3 method for class 'rmsb' plot( x, which = NULL, nrow = NULL, ncol = NULL, prob = 0.95, bivar = FALSE, bivarmethod = c("ellipse", "kernel"), ... )
x |
an |
which |
names of parameters to plot, defaulting to all non-intercepts. Can instead be a vector of integers. |
nrow |
number of rows of plots |
ncol |
number of columns of plots |
prob |
probability for HPD interval |
bivar |
set to |
bivarmethod |
passed as |
... |
passed to |
ggplot2 object
Frank Harrell
From a Bayesian fit object such as that from blrm() generates an R function for evaluating the probability that an assertion is true. The probability, within simulation error, is the proportion of times the assertion is true over the posterior draws. If the assertion does not evaluate to a logical or 0/1 quantity, it is taken as a continuous derived parameter and the vector of draws for that parameter is returned and can be passed to the PostF plot method. PostF can also be used on objects created by contrast.rms
PostF(fit, name = c("short", "orig"), pr = FALSE)PostF(fit, name = c("short", "orig"), pr = FALSE)
fit |
a Bayesian fit or |
name |
specifies whether assertions will refer to shortened parameter names (the default) or original names. Shorted names are of the form |
pr |
set to |
an R function
Frank Harrell
## Not run: f <- blrm(y ~ age + sex) P <- PostF(f) P(b2 > 0) # Model is a1 + b1*age + b2*(sex == 'male') P(b1 < 0 & b2 > 0) # Post prob of a compound assertion # To compute probabilities using original parameter names: P <- PostF(f, name='orig') P(age < 0) # Post prob of negative age effect P(`sex=male` > 0) f <- blrm(y ~ sex + pol(age, 2)) P <- PostF(f) # Compute and plot posterior density of the vertex of the # quadratic age effect plot(P(-b2 / (2 * b3))) # The following would be useful in age and sex interacted k <- contrast(f, list(age=c(30, 50), sex='male'), list(age=c(30, 50), sex='female'), cnames=c('age 30 M-F', 'age 50 M-F')) P <- PostF(k) P(`age 30 M-F` > 0 & `age 50 M-F` > 0) ##' ## End(Not run)## Not run: f <- blrm(y ~ age + sex) P <- PostF(f) P(b2 > 0) # Model is a1 + b1*age + b2*(sex == 'male') P(b1 < 0 & b2 > 0) # Post prob of a compound assertion # To compute probabilities using original parameter names: P <- PostF(f, name='orig') P(age < 0) # Post prob of negative age effect P(`sex=male` > 0) f <- blrm(y ~ sex + pol(age, 2)) P <- PostF(f) # Compute and plot posterior density of the vertex of the # quadratic age effect plot(P(-b2 / (2 * b3))) # The following would be useful in age and sex interacted k <- contrast(f, list(age=c(30, 50), sex='male'), list(age=c(30, 50), sex='female'), cnames=c('age 30 M-F', 'age 50 M-F')) P <- PostF(k) P(`age 30 M-F` > 0 & `age 50 M-F` > 0) ##' ## End(Not run)
blrm() fitPredict method for blrm() objects
## S3 method for class 'blrm' predict( object, ..., kint = NULL, ycut = NULL, zcppo = TRUE, Zmatrix = TRUE, fun = NULL, funint = TRUE, type = c("lp", "fitted", "fitted.ind", "mean", "x", "data.frame", "terms", "cterms", "ccterms", "adjto", "adjto.data.frame", "model.frame"), se.fit = FALSE, codes = FALSE, posterior.summary = c("mean", "median", "all"), cint = 0.95 )## S3 method for class 'blrm' predict( object, ..., kint = NULL, ycut = NULL, zcppo = TRUE, Zmatrix = TRUE, fun = NULL, funint = TRUE, type = c("lp", "fitted", "fitted.ind", "mean", "x", "data.frame", "terms", "cterms", "ccterms", "adjto", "adjto.data.frame", "model.frame"), se.fit = FALSE, codes = FALSE, posterior.summary = c("mean", "median", "all"), cint = 0.95 )
object, ..., type, se.fit, codes
|
|
kint |
This is only useful in a multiple intercept model such as the ordinal logistic model. There to use to second of three intercepts, for example, specify |
ycut |
for an ordinal model specifies the Y cutoff to use in evaluating departures from proportional odds, when the constrained partial proportional odds model is used. When omitted, |
zcppo |
applies only to |
Zmatrix |
set to |
fun |
a function to evaluate on the linear predictor, e.g. a function created by |
funint |
set to |
posterior.summary |
set to |
cint |
probability for highest posterior density interval. Set to |
a data frame, matrix, or vector with posterior summaries for the requested quantity, plus an attribute 'draws' that has all the posterior draws for that quantity. For type='fitted' and type='fitted.ind' this attribute is a 3-dimensional array representing draws x observations generating predictions x levels of Y.
Frank Harrell
## Not run: f <- blrm(...) predict(f, newdata, type='...', posterior.summary='median') ## End(Not run)## Not run: f <- blrm(...) predict(f, newdata, type='...', posterior.summary='median') ## End(Not run)
blrm() ResultsPrints main results from blrm() along with indexes and predictive accuracy and their highest posterior density intervals computed from blrmStats.
## S3 method for class 'blrm' print( x, dec = 4, coefs = TRUE, intercepts = x$non.slopes < 10, prob = 0.95, ns = 400, title = NULL, ... )## S3 method for class 'blrm' print( x, dec = 4, coefs = TRUE, intercepts = x$non.slopes < 10, prob = 0.95, ns = 400, title = NULL, ... )
x |
object created by |
dec |
number of digits to print to the right of the decimal |
coefs |
specify |
intercepts |
set to |
prob |
HPD interval probability for summary indexes |
ns |
number of random samples of the posterior draws for use in computing HPD intervals for accuracy indexes |
title |
title of output, constructed by default |
... |
passed to |
Frank Harrell
## Not run: f <- blrm(...) options(lang='html') # default is lang='plain'; also can be latex f # print using defaults print(f, posterior.summary='median') # instead of post. means ## End(Not run)## Not run: f <- blrm(...) options(lang='html') # default is lang='plain'; also can be latex f # print using defaults print(f, posterior.summary='median') # instead of post. means ## End(Not run)
blrmStats Predictive Accuracy MeasuresPrints results of blrmStats with brief explanations
## S3 method for class 'blrmStats' print(x, dec = 3, ...)## S3 method for class 'blrmStats' print(x, dec = 3, ...)
x |
an object produced by |
dec |
number of digits to round indexes |
... |
ignored |
Frank Harrell
## Not run: f <- blrm(...) s <- blrmStats(...) s # print with defaults print(s, dec=4) ## End(Not run)## Not run: f <- blrm(...) s <- blrmStats(...) s # print with defaults print(s, dec=4) ## End(Not run)
blrm()
Prints the summary portion of the results of predict.blrm
## S3 method for class 'predict.blrm' print(x, digits = 3, ...)## S3 method for class 'predict.blrm' print(x, digits = 3, ...)
x |
result from |
digits |
number of digits to round numeric results |
... |
ignored |
Frank Harrell
For a Bayesian regression fit prints the posterior mean, median, SE, highest posterior density interval, and symmetry coefficient from the posterior draws. For a given parameter, the symmetry measure is computed using the distSym function.
## S3 method for class 'rmsb' print(x, prob = 0.95, dec = 4, intercepts = TRUE, pr = TRUE, ...)## S3 method for class 'rmsb' print(x, prob = 0.95, dec = 4, intercepts = TRUE, pr = TRUE, ...)
x |
an object created by an |
prob |
HPD interval coverage probability (default is 0.95) |
dec |
amount of rounding (digits to the right of the decimal) |
intercepts |
set to |
pr |
set to |
... |
ignored |
matrix (rounded if pr=TRUE)
Frank Harrell
## Not run: f <- blrm(...) print.rmsb(f) ## End(Not run)## Not run: f <- blrm(...) print.rmsb(f) ## End(Not run)
blrm()
Creates a function to turn a posterior summarized linear predictor lp (e.g. using posterior mean of intercepts and slopes) computed at the reference intercept into e.g. an estimate of a quantile of Y using the posterior mean of all the intercepts. lptau must be provided when call the created function if the model is a partial proportional odds model.
## S3 method for class 'blrm' Quantile(object, codes = FALSE, posterior.summary = c("mean", "median"), ...)## S3 method for class 'blrm' Quantile(object, codes = FALSE, posterior.summary = c("mean", "median"), ...)
object |
a |
codes |
if |
posterior.summary |
defaults to posterior mean; may also specify |
... |
ignored |
an R function
Frank Harrell
Runs a matrix through the QR decomposition and returns the transformed matrix and the forward and inverse transforming matrices R, Rinv. If columns of the input matrix X are centered the QR transformed matrix will be orthogonal. This is helpful in understanding the transformation and in scaling prior distributions on the transformed scale. not can be specified to keep selected columns as-is. cornerQr leaves the last column of X alone (possibly after centering). When not is specified, the square transforming matrices have appropriate identity submatrices inserted so that recreation of original X is automatic.
selectedQr(X, not = NULL, corner = FALSE, center = TRUE)selectedQr(X, not = NULL, corner = FALSE, center = TRUE)
X |
a numeric matrix |
not |
an integer vector specifying which columns of |
corner |
set to |
center |
set to |
list with elements X, R, Rinv, xbar where xbar is the vector of means (vector of zeros if center=FALSE)
Ben Goodrich and Frank Harrell
x <- 1 : 10 X <- cbind(x, x^2) w <- selectedQr(X) w with(w, X %*% R) # = scale(X, center=TRUE, scale=FALSE) Xqr <- w$X plot(X[, 1], Xqr[, 1]) plot(X[, 1], Xqr[, 2]) cov(X) cov(Xqr) X <- cbind(x, x^3, x^4, x^2) w <- selectedQr(X, not=2:3) with(w, X %*% R)x <- 1 : 10 X <- cbind(x, x^2) w <- selectedQr(X) w with(w, X %*% R) # = scale(X, center=TRUE, scale=FALSE) Xqr <- w$X plot(X[, 1], Xqr[, 1]) plot(X[, 1], Xqr[, 2]) cov(X) cov(Xqr) X <- cbind(x, x^3, x^4, x^2) w <- selectedQr(X, not=2:3) with(w, X %*% R)
Runs an rmsb package Bayesian fitting function such as blrm separately for each completed dataset given a multiple imputation result such as one produced by Hmisc::aregImpute. Stacks the posterior draws and diagnostics across all imputations, and computes parameter summaries on the stacked posterior draws.
stackMI( formula, fitter, xtrans, data = NULL, n.impute = xtrans$n.impute, dtrans = NULL, derived = NULL, subset = NULL, refresh = 0, progress = if (refresh > 0) "stan-progress.txt" else "", file = NULL, ... )stackMI( formula, fitter, xtrans, data = NULL, n.impute = xtrans$n.impute, dtrans = NULL, derived = NULL, subset = NULL, refresh = 0, progress = if (refresh > 0) "stan-progress.txt" else "", file = NULL, ... )
formula |
a model formula |
fitter |
a Bayesian fitter |
xtrans |
an object created by |
data |
data frame |
n.impute |
number of imputations to run, default is the number saved in |
dtrans |
see |
derived |
see |
subset |
an integer or logical vector specifying the subset of observations to fit |
refresh |
see rstan::sampling. The default is 0, indicating that no progress notes are output. If |
progress |
see |
file |
optional file name in which to store results in RDS format. If |
... |
arguments passed to |
an rmsb fit object with expanded posterior draws and diagnostics
Frank Harrell
Retrieves the effect samples sizes and Rhats computed after a fitting function ran rstan, and prepares it for printing. If the fit was created by stackImpute, the diagnostics for all imputations are printed (separately).
stanDx(object)stanDx(object)
object |
an object created by an |
matrix suitable for printing
Frank Harrell
## Not run: f <- blrm(...) stanDx(f) ## End(Not run)## Not run: f <- blrm(...) stanDx(f) ## End(Not run)
For an rms Bayesian fit object, uses by default the stored posterior draws to check convergence properties of posterior sampling. If instead rstan=TRUE, calls the rstan traceplot function on the rstan object inside the rmsb object, to check properties of posterior sampling. If rstan=TRUE and the rstan object has been removed and previous=TRUE, attempts to find an already existing plot created by a previous run of the knitr chunk, assuming it was the plotno numbered plot of the chunk.
stanDxplot( x, which = NULL, rstan = FALSE, previous = TRUE, plotno = 1, rev = FALSE, stripsize = 8, ... )stanDxplot( x, which = NULL, rstan = FALSE, previous = TRUE, plotno = 1, rev = FALSE, stripsize = 8, ... )
x |
an |
which |
names of parameters to plot, defaulting to all non-intercepts. When |
rstan |
set to |
previous |
see details |
plotno |
see details |
rev |
set to |
stripsize |
specifies size of chain facet label text, default is 8 |
... |
passed to |
ggplot2 object if rstan object was in x
Frank Harrell
Extracts the object created by rstan::sampling() so that standard Stan diagnostics can be run from it
stanGet(object)stanGet(object)
object |
an objected created by an |
the object created by rstan::sampling()
Frank Harrell
## Not run: f <- blrm(...) s <- stanGet(f) ## End(Not run)## Not run: f <- blrm(...) s <- stanGet(f) ## End(Not run)
Fetches matrix of posterior draws for partial proportional odds parameters (taus) for a given intercept. Can also form a matrix containing both regular parameters and taus, or for just non-taus. For the constrained partial proportional odds model the function returns the appropriate cppo function value multiplied by tau (tau being a vector in this case and not a matrix).
tauFetch(fit, intercept, what = c("tau", "nontau", "both"))tauFetch(fit, intercept, what = c("tau", "nontau", "both"))
fit |
an object created by |
intercept |
integer specifying which intercept to fetch |
what |
specifies the result to return |
matrix with number of raws equal to the numnber of original draws
Frank Harrell
Computes the variance-covariance matrix from the posterior draws by compute the sample covariance matrix of the draws
## S3 method for class 'rmsb' vcov(object, regcoef.only = TRUE, intercepts = "all", ...)## S3 method for class 'rmsb' vcov(object, regcoef.only = TRUE, intercepts = "all", ...)
object |
an object produced by an |
regcoef.only |
set to |
intercepts |
set to |
... |
ignored |
matrix
Frank Harrell
## Not run: f <- blrm(...) v <- vcov(f) ## End(Not run)## Not run: f <- blrm(...) v <- vcov(f) ## End(Not run)