| Title: | Integration of 'Blimp' Software into R |
|---|---|
| Description: | Provides an interface to 'Blimp' software for Bayesian latent variable modeling, missing data analysis, and multiple imputation. The package generates 'Blimp' syntax, executes 'Blimp' models, and imports results back into 'R' as structured objects with methods for visualization and analysis. Requires 'Blimp' software (freely available at <https://www.appliedmissingdata.com/blimp>) to be installed separately. |
| Authors: | Brian T. Keller [aut, cre, cph] |
| Maintainer: | Brian T. Keller <[email protected]> |
| License: | GPL-3 |
| Version: | 1.2.5 |
| Built: | 2026-10-15 20:38:40 UTC |
| Source: | https://github.com/blimp-stats/rblimp |
Extracts the algorithmic options section from Blimp output.
algorithm(object)algorithm(object)
object |
A |
A blimp_out object containing algorithmic options
S3 methods for the posterior::as_draws() family of generics, allowing
blimp_obj to be used anywhere a posterior::draws object is expected.
This is the gateway to the posterior and bayesplot ecosystems:
once converted, the usual summarise_draws(), mcmc_trace(),
mcmc_areas(), etc., all work.
The posterior package must be installed to use these methods. It is
listed in Suggests, so install it explicitly with
install.packages("posterior") if needed.
## S3 method for class 'blimp_obj' as_draws(x, warmup = c("exclude", "include", "only"), ...) ## S3 method for class 'blimp_obj' as_draws_array(x, warmup = c("exclude", "include", "only"), ...) ## S3 method for class 'blimp_obj' as_draws_df(x, warmup = c("exclude", "include", "only"), ...)## S3 method for class 'blimp_obj' as_draws(x, warmup = c("exclude", "include", "only"), ...) ## S3 method for class 'blimp_obj' as_draws_array(x, warmup = c("exclude", "include", "only"), ...) ## S3 method for class 'blimp_obj' as_draws_df(x, warmup = c("exclude", "include", "only"), ...)
x |
A |
warmup |
One of |
... |
Additional arguments (unused). |
All three methods accept a warmup argument with the same semantics as
as.array,blimp_obj-method. Because draws_array objects do not carry
a separate warmup/sampling distinction, the "n_warmup" attribute set by
as.array(x, warmup = "include") is dropped during conversion; users who
need the warmup marker should convert via as.array() and pass the
result to bayesplot::mcmc_trace() directly.
An object of class posterior::draws_array (for as_draws and
as_draws_array) or posterior::draws_df (for as_draws_df).
mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) model <- rblimp( list(structure = 'y ~ f', measurement = 'f -> x1:x5'), mydata, chains = 4, seed = 3927, latent = ~ f ) draws <- posterior::as_draws_array(model) posterior::summarise_draws(draws) ## Not run: if (requireNamespace("bayesplot", quietly = TRUE)) { bayesplot::mcmc_trace(draws) bayesplot::mcmc_areas(draws) } ## End(Not run)mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) model <- rblimp( list(structure = 'y ~ f', measurement = 'f -> x1:x5'), mydata, chains = 4, seed = 3927, latent = ~ f ) draws <- posterior::as_draws_array(model) posterior::summarise_draws(draws) ## Not run: if (requireNamespace("bayesplot", quietly = TRUE)) { bayesplot::mcmc_trace(draws) bayesplot::mcmc_areas(draws) } ## End(Not run)
Reshapes the MCMC draws in a blimp_obj into a 3-D numeric array with
dimensions [iteration, chain, parameter]. This is the format consumed
directly by bayesplot::mcmc_* functions and by posterior::as_draws_array().
## S4 method for signature 'blimp_obj' as.array(x, warmup = c("exclude", "include", "only"), ...)## S4 method for signature 'blimp_obj' as.array(x, warmup = c("exclude", "include", "only"), ...)
x |
A |
warmup |
One of |
... |
Additional arguments (unused). |
The warmup argument controls whether burn-in draws are included:
"exclude"(default) returns only post-burn sampling draws.
"include"returns warmup draws stacked on top of sampling
draws within each chain. The returned array carries an
"n_warmup" attribute giving the number of warmup iterations, so
it can be piped directly into
bayesplot::mcmc_trace(arr, n_warmup = attr(arr, "n_warmup")).
"only"returns only warmup draws.
A numeric 3-D array with dimensions [iteration, chain, parameter],
named dimnames, and (when warmup = "include") an "n_warmup"
attribute.
as_draws_array.blimp_obj() for the posterior::draws_array
equivalent.
# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit model model <- rblimp( list(structure = 'y ~ f', measurement = 'f -> x1:x5'), mydata, chains = 4, seed = 3927, latent = ~ f ) # Post-burn only (default) arr <- as.array(model) dim(arr) dimnames(arr)$parameters # Include warmup, feed to bayesplot with its n_warmup marker ## Not run: if (requireNamespace("bayesplot", quietly = TRUE)) { arr_full <- as.array(model, warmup = "include") bayesplot::mcmc_trace(arr_full, n_warmup = attr(arr_full, "n_warmup")) } ## End(Not run)# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit model model <- rblimp( list(structure = 'y ~ f', measurement = 'f -> x1:x5'), mydata, chains = 4, seed = 3927, latent = ~ f ) # Post-burn only (default) arr <- as.array(model) dim(arr) dimnames(arr)$parameters # Include warmup, feed to bayesplot with its n_warmup marker ## Not run: if (requireNamespace("bayesplot", quietly = TRUE)) { arr_full <- as.array(model, warmup = "include") bayesplot::mcmc_trace(arr_full, n_warmup = attr(arr_full, "n_warmup")) } ## End(Not run)
blimp_syntax to character vectorConvert blimp_syntax to character vector
## S3 method for class 'blimp_syntax' as.character(x, ...)## S3 method for class 'blimp_syntax' as.character(x, ...)
x |
A |
... |
Additional arguments (unused) |
A character string containing the formatted 'Blimp' input syntax with a header comment and all commands.
Convert blimp_obj to data.frame
## S4 method for signature 'blimp_obj' as.data.frame(x, row.names = NULL, optional = FALSE, ...)## S4 method for signature 'blimp_obj' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
A |
row.names |
NULL or a character vector giving row names |
optional |
Logical. If TRUE, setting row names is optional |
... |
Additional arguments passed to as.data.frame |
A data.frame containing the MCMC iterations from the model.
Convert blimp_obj to matrix
## S4 method for signature 'blimp_obj' as.matrix(x, ...)## S4 method for signature 'blimp_obj' as.matrix(x, ...)
x |
A |
... |
Additional arguments (unused) |
A numeric matrix containing the MCMC iterations from the model.
blimp_obj or blimp_bygroup to a mitml.list
Coerces a blimp_obj or blimp_bygroup to a mitml.list
as.mitml(object)as.mitml(object)
object |
|
A list of class "mitml.list" containing the imputed data sets,
suitable for use with functions from the 'mitml' package.
Used inside simple_plot and jn_plot formulas to restrict the SIMPLE
rows to those whose moderator was evaluated at the given label(s).
at(...)at(...)
... |
named arguments where each name is a moderator in the SIMPLE
command and each value is a single label or a vector of labels
(e.g., |
If at() is the only term after |, the moderators it names are also the
ones plotted, so y ~ x | at(m = c("-1 SD", "+1 SD")) shows just those two
values of m without having to name m twice.
Calling at() outside a formula raises an error; the function only
has meaning when it appears in a simple_plot() or jn_plot() formula.
simple_plot, jn_plot, jn_map, join
## Not run: # Pin `m2` at the SIMPLE label "0", leaving `m1` to color the lines simple_plot(y ~ x | m1 + at(m2 = "0"), model) # Pin to a subset (vector of labels) -- `m2` still faces over those values simple_plot(y ~ x | m1 + at(m2 = c("Q25", "Q75")), model) # Show only some of a single moderator's values (no bare name needed) simple_plot(y ~ x | at(m1 = c("Q25", "Q50", "Q75")), model) # Use inside `jn_plot()` the same way jn_plot(y ~ x | m1 + at(m2 = "+1 SD"), model) # In a 4-way fit, pin one moderator and map the slope surface over the other two jn_map(y ~ x | m1 + m2 + at(m3 = "0"), four_way_model) ## End(Not run)## Not run: # Pin `m2` at the SIMPLE label "0", leaving `m1` to color the lines simple_plot(y ~ x | m1 + at(m2 = "0"), model) # Pin to a subset (vector of labels) -- `m2` still faces over those values simple_plot(y ~ x | m1 + at(m2 = c("Q25", "Q75")), model) # Show only some of a single moderator's values (no bare name needed) simple_plot(y ~ x | at(m1 = c("Q25", "Q50", "Q75")), model) # Use inside `jn_plot()` the same way jn_plot(y ~ x | m1 + at(m2 = "+1 SD"), model) # In a 4-way fit, pin one moderator and map the slope surface over the other two jn_map(y ~ x | m1 + m2 + at(m3 = "0"), four_way_model) ## End(Not run)
Result object from comparing two Blimp models.
tableMatrix of comparison results
model0The reference blimp_obj model
modelThe comparison blimp_obj model
greaterThanLogical indicating direction of comparison
The main result object containing Blimp model estimates, iterations, and output.
callThe function call that created the object
estimatesMatrix of parameter estimates
burnList of burn-in information for each chain
iterationsData frame of MCMC iterations
psrData frame of Potential Scale Reduction values
imputationsList of imputed datasets
average_impData frame of average imputations
variance_impData frame of imputation variances
waldtestData frame of Wald test results
simpleData frame for simple slopes analysis
syntaxThe blimp_syntax object used to run the model
outputThe blimp_out object containing raw output text
rblimp's plots draw with the colors, line widths, point sizes, and fonts of the
plot's ggplot2 theme. blimp_style() sets the
remaining defaults: transparency, summary markers, reference lines, labels, and
Johnson-Neyman lines and boundaries. Add it to a plot or a theme, as with
ggplot2::theme.
blimp_style( ..., point_alpha = NULL, data_color = NULL, summary_size = NULL, summary_shape = NULL, ribbon_alpha = NULL, area_alpha = NULL, curve_alpha = NULL, reference_color = NULL, guide_color = NULL, label_color = NULL, boundary_color = NULL, boundary_alpha = NULL, boundary_linewidth = NULL )blimp_style( ..., point_alpha = NULL, data_color = NULL, summary_size = NULL, summary_shape = NULL, ribbon_alpha = NULL, area_alpha = NULL, curve_alpha = NULL, reference_color = NULL, guide_color = NULL, label_color = NULL, boundary_color = NULL, boundary_alpha = NULL, boundary_linewidth = NULL )
... |
the color arguments spelled |
point_alpha |
a number in [0, 1]. Transparency of the points in the diagnostic plots. Unset, a point cloud that stacks M imputations uses 0.7 / M^(1/3) and other points use 0.7. |
data_color |
a color for imputed and model-implied values: the points and bars in
the diagnostic plots (residuals are model-implied; except points colored by category),
the imputed values marked by |
summary_size |
a positive number. Size of the category-mean markers in
|
summary_shape |
a point shape, as a number or name. Shape of the category-mean
markers. Unset: a diamond (18) in |
ribbon_alpha |
a number in [0, 1]. Transparency of interval bands. Unset:
0.2 in |
area_alpha |
a number in [0, 1]. Transparency of filled areas. Unset: 0.25
for the densities in |
curve_alpha |
a number in [0, 1]. Transparency of the per-imputation density curves
in |
reference_color |
a color. Reference lines: the zero lines in the diagnostic
plots, |
guide_color |
a color. The guide lines at 1, 2, and 3 standard deviations in
the within-cluster spread plot of |
label_color |
a color. Text labels for cases and influence cutoffs. Unset:
|
boundary_color |
a color. Johnson-Neyman boundaries: the boundary segments
in |
boundary_alpha |
a number in [0, 1]. Transparency of the Johnson-Neyman
boundaries. Unset: 0.5 in |
boundary_linewidth |
a positive number. Line width of the Johnson-Neyman
boundaries. Unset: the theme's line width in |
Each argument sets the theme setting blimp.<argument>, with the underscore
replaced by a dot: blimp_style(point_alpha = 0.2) is the same as
ggplot2::theme(blimp.point.alpha = 0.2). In ggplot2::theme(), color settings use
the color spelling (blimp.reference.color). A setting that is not
set keeps each plot's own default, listed above. blimp_style() checks its values
right away; values given to ggplot2::theme() directly are checked only when the
plot is drawn.
Everything else follows the ggplot2 theme (ggplot2::element_geom). Lines use the
theme's geom color (its ink unless the theme sets colour) and line width (dashed
reference lines in the diagnostic plots are half of it and curves twice it), points
its point size, curves its accent color, and text its font. In distribution_plot,
the observed-value bars use the theme's geom fill, or the first color of its discrete
fill palette when the theme sets no fill; a fill or colour scale added to the plot
takes precedence over both. Groups use the theme's discrete palettes, and the fill of
jn_map uses its continuous fill palette (palette.fill.continuous) with 0 at the
palette's middle color, falling back to a blue-white-red scale.
Requires ggplot2 4.0 or later.
a ggplot2::theme that sets the given settings.
theme_blimp, residual_plot, distribution_plot, jn_plot,
jn_map, simple_plot, posterior_plot
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 20, seed = 10972, burn = 1000, iter = 1000) # One plot residual_plot(m1, 'y', x = 'x') + blimp_style(point_alpha = 0.1, reference_color = 'red') # Every plot in the session old <- ggplot2::theme_set(ggplot2::theme_minimal() + blimp_style(point_alpha = 0.1)) residual_plot(m1, 'y', x = 'x') ggplot2::theme_set(old)# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 20, seed = 10972, burn = 1000, iter = 1000) # One plot residual_plot(m1, 'y', x = 'x') + blimp_style(point_alpha = 0.1, reference_color = 'red') # Every plot in the session old <- ggplot2::theme_set(ggplot2::theme_minimal() + blimp_style(point_alpha = 0.1)) residual_plot(m1, 'y', x = 'x') ggplot2::theme_set(old)
rblimp based on grouping variablerblimp will generate the input, run the script, and load most the saved data into an R object. rblimp_fcs
is used to specify the FCS command in Blimp. rblimp_syntax will generate the Blimp syntax file only.
by_group(expr, group)by_group(expr, group)
expr |
a call to |
group |
a character vector or index pointing to grouping variable in data set |
Separates by grouping to run blimp command on each individual sub data set.
a list of all blimp runs by group with class of blimp_bygroup
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(0, 1)', 'group = uniform(0, 1) < 0.5' ), n = 1000, seed = 10972 ) # Nonsensical model mdl <- rblimp_fcs( c('x', 'y'), mydata, seed = 3927, nimps = 2, ) |> by_group('group') # Analyze each imputation results <- with(mdl, lm(y ~ x)) # use `mitml` package to pool results# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(0, 1)', 'group = uniform(0, 1) < 0.5' ), n = 1000, seed = 10972 ) # Nonsensical model mdl <- rblimp_fcs( c('x', 'y'), mydata, seed = 3927, nimps = 2, ) |> by_group('group') # Analyze each imputation results <- with(mdl, lm(y ~ x)) # use `mitml` package to pool results
Compares two Bayesian models by calculating the proportion of posterior samples where the comparison model's parameters exceed (or fall below) the reference model's summary statistic. This is useful for model comparison and assessing incremental variance explained (e.g., R-squared differences).
compare( model0, model, use = "mean", greaterThan = TRUE, suffixes = c("R2: Coefficients", "R2: Level-2 Random Intercepts", "R2: Level-2 Random Slopes", "R2: Level-3 Random Slopes", "R2: Level-3 Random Intercepts", "R2: Residual Variation", "R2: Level-1 Residual Variation") )compare( model0, model, use = "mean", greaterThan = TRUE, suffixes = c("R2: Coefficients", "R2: Level-2 Random Intercepts", "R2: Level-2 Random Slopes", "R2: Level-3 Random Slopes", "R2: Level-3 Random Intercepts", "R2: Residual Variation", "R2: Level-1 Residual Variation") )
model0 |
A |
model |
A |
use |
Summary statistic to use as the cutpoint from
|
greaterThan |
Logical. If |
suffixes |
Character vector of parameter name suffixes to compare. Defaults to all R-squared values (coefficients, random effects, residual variation). |
The comparison works by:
Computing a summary statistic (e.g., mean) from model0's posterior samples
Calculating what proportion of model's posterior samples exceed this value
Reporting this proportion for each parameter matching the specified suffixes
A blimp_cp object containing a matrix of comparison proportions.
Due to R restrictions, lists of functions will not give useful printed names.
# Generate data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.3*x2, 1)' ), n = 200, seed = 123 ) # Fit baseline model (x1 only) model0 <- rblimp( 'y ~ x1', mydata, seed = 123, burn = 1000, iter = 1000 ) # Fit comparison model (x1 + x2) model1 <- rblimp( 'y ~ x1 x2', mydata, seed = 123, burn = 1000, iter = 1000 ) # Compare models - proportion of model1 R-squared > mean(model0 R-squared) compare(model0, model1)# Generate data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.3*x2, 1)' ), n = 200, seed = 123 ) # Fit baseline model (x1 only) model0 <- rblimp( 'y ~ x1', mydata, seed = 123, burn = 1000, iter = 1000 ) # Fit comparison model (x1 + x2) model1 <- rblimp( 'y ~ x1 x2', mydata, seed = 123, burn = 1000, iter = 1000 ) # Compare models - proportion of model1 R-squared > mean(model0 R-squared) compare(model0, model1)
jn_plot_func
Convenience Function for computing conditional effects for jn_plot_func
compute_condeff(value1, value2)compute_condeff(value1, value2)
value1 |
The base value |
value2 |
The value to change as a function of moderator |
a function
# Generate Data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.5*x2 + m + 0.2*x1*x2 + 0.3*x2*m + 0.1*x1*m + 0.7*x1*x2*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x1 x2 m x1*x2 x1*m x2*m x1*x2*m', mydata, center = ~ m, seed = 10972, burn = 1000, iter = 1000 ) # Get parameter values params <- m1 |> as.matrix() # Generate Plot ( jn_plot_func( compute_condeff(params[,6], params[,9]), xrange = c(-3, 3) ) # Set custom colors + ggplot2::scale_fill_manual( values = c(`FALSE` = '#ca0020', `TRUE` = '#0571b0') ) + ggplot2::labs( title = 'Johnson-Neyman Plot for `x1` * `x2` Moderated by `x2`', subtitle = 'Shading shows whether 0 is within the 95% interval', y = 'y ~ x1 * x2', x = 'm' ) + ggplot2::theme_minimal() )# Generate Data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.5*x2 + m + 0.2*x1*x2 + 0.3*x2*m + 0.1*x1*m + 0.7*x1*x2*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x1 x2 m x1*x2 x1*m x2*m x1*x2*m', mydata, center = ~ m, seed = 10972, burn = 1000, iter = 1000 ) # Get parameter values params <- m1 |> as.matrix() # Generate Plot ( jn_plot_func( compute_condeff(params[,6], params[,9]), xrange = c(-3, 3) ) # Set custom colors + ggplot2::scale_fill_manual( values = c(`FALSE` = '#ca0020', `TRUE` = '#0571b0') ) + ggplot2::labs( title = 'Johnson-Neyman Plot for `x1` * `x2` Moderated by `x2`', subtitle = 'Shading shows whether 0 is within the 95% interval', y = 'y ~ x1 * x2', x = 'm' ) + ggplot2::theme_minimal() )
blimp_obj
Cook's distance from blimp_obj
## S4 method for signature 'blimp_obj' cooks.distance(model, ...)## S4 method for signature 'blimp_obj' cooks.distance(model, ...)
model |
A |
... |
Additional arguments (unused) |
Values are computed by Blimp and averaged over every post burn-in iteration. Only single-level continuous and ordinal probit outcomes are included.
A data frame with one row per case and a <dv>.cooks column for each eligible outcome.
Extracts the data information section from Blimp output.
datainfo(object)datainfo(object)
object |
A |
A blimp_out object containing data information
describe provides a flexible summary of various R objects,
such as data frames or Blimp model objects. It is an
alternative to summary and is inspired by precis from the rethinking package.
describe( object, depth = 1, pars, prob = 0.95, digits = 2, sort = NULL, decreasing = FALSE, ... ) ## S4 method for signature 'data.frame' describe( object, depth = 1, pars, prob = 0.5, digits = 2, sort = NULL, decreasing = FALSE, hist = TRUE, ... ) ## S4 method for signature 'blimp_obj' describe( object, depth = 1, pars, prob = 0.95, digits = 2, sort = NULL, decreasing = FALSE, hist = TRUE, ... )describe( object, depth = 1, pars, prob = 0.95, digits = 2, sort = NULL, decreasing = FALSE, ... ) ## S4 method for signature 'data.frame' describe( object, depth = 1, pars, prob = 0.5, digits = 2, sort = NULL, decreasing = FALSE, hist = TRUE, ... ) ## S4 method for signature 'blimp_obj' describe( object, depth = 1, pars, prob = 0.95, digits = 2, sort = NULL, decreasing = FALSE, hist = TRUE, ... )
object |
The object to describe. |
depth |
An integer ( |
pars |
An optional character vector of parameter names to include in the summary. |
prob |
The probability mass for the credible interval (e.g., quantile interval). |
digits |
The number of decimal places to display in the output. |
sort |
An optional character string specifying a column name to sort the results by. |
decreasing |
Logical. If |
... |
Additional arguments passed to specific methods. |
hist |
Logical. If |
An object of class describe, which is a data frame containing summary statistics and attributes for printing.
The data.frame method is adapted from Richard McElreath's precis
function in the rethinking package (https://github.com/rmcelreath/rethinking).
The histospark function is by Hadley Wickham (GPL-3).
The blimp_obj method was written for this package.
An S4 class that holds a summary data frame and formatting
information. It extends the data.frame class and is the return type for
the describe() function.
## S4 method for signature 'describe' show(object)## S4 method for signature 'describe' show(object)
object |
An object of class |
digitsA numeric value indicating the number of digits to display.
This function is called when running Blimp and can be used to determine what location
rblimp uses for the Blimp executable.
detect_blimp(prompt = TRUE)detect_blimp(prompt = TRUE)
prompt |
Logical; when |
rblimp resolves Blimp's executable location in this order:
Any location previously set via set_blimp.
The R_BLIMP environment variable.
A managed install created by install_blimp.
The default operating-system install location of the Blimp system installer.
If none are found and the R session is interactive, detect_blimp
offers to download and install Blimp via install_blimp (unless
prompt = FALSE).
A character string of blimp's executable location.
set_blimp to set blimp location, install_blimp
to install Blimp into a managed directory.
# Obtain blimp location detect_blimp()# Obtain blimp location detect_blimp()
blimp_obj
Builds every residual and influence plot that applies to each outcome in a model, as a
named list of ggplot2::ggplot plots. Each element is one call to residual_plot,
influence_plot, or probability_plot.
diagnostic_plots(model, selector, discrete_max_unique = 10L, bars = TRUE) ## S3 method for class 'diagnostic_plots' print(x, ...) ## S3 method for class 'diagnostic_plots' x[i] ## S3 method for class 'diagnostic_plots' subset(x, pattern, ...) ## S3 method for class 'diagnostic_plots' e1 + e2 ## S3 method for class 'diagnostic_plots' e1 & e2diagnostic_plots(model, selector, discrete_max_unique = 10L, bars = TRUE) ## S3 method for class 'diagnostic_plots' print(x, ...) ## S3 method for class 'diagnostic_plots' x[i] ## S3 method for class 'diagnostic_plots' subset(x, pattern, ...) ## S3 method for class 'diagnostic_plots' e1 + e2 ## S3 method for class 'diagnostic_plots' e1 & e2
model |
a |
selector |
an optional character vector of outcome names. If missing, every outcome with saved residuals is included. |
discrete_max_unique |
an integer, passed to |
bars |
passed to |
x |
a |
... |
for |
i |
indices or names of the plots to keep. |
pattern |
a regular expression matched against the plot names. |
e1, e2
|
a |
The plots for each outcome depend on its type:
| Outcome | Elements |
| Continuous, ordinal | <dv>.predicted, <dv>.<predictor>, <dv>.index, <dv>.leverage, <dv>.cooks |
| Ordinal | also <dv>.<predictor>.probability |
| Continuous, clustered | also <dv>.cluster_variance |
| Nominal | <dv>.<k>.binned, <dv>.<k>.<predictor> for each non-reference category k; <dv>.<predictor>.probability |
| Count | <dv>.index, <dv>.<predictor> (Pearson residuals) |
| Level-2 residual or latent | <name>.index, <name>.<level-2 predictor>
|
Leverage and Cook's distance require Blimp 4.1.0 or later; without them, every other plot is drawn and a warning says so.
Element names are for browsing. To build a specific figure, call the single-plot
function directly, e.g. residual_plot(model, "y", x = "x1").
A named list of plots with class diagnostic_plots. Printing it draws every plot.
+ and & add a ggplot2 component to every plot (the list must be on the left), and
[ and subset() keep the class. subset(x, pattern) keeps the plots whose names
match pattern, e.g. subset(plots, "index") or plots |> subset("x1").
residual_plot, influence_plot, probability_plot, distribution_plots
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Every diagnostic, restyled at once plots <- diagnostic_plots(m1) + ggplot2::theme_minimal() names(plots) plots$y.index # Only the index plots diagnostic_plots(m1) |> subset("index")# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Every diagnostic, restyled at once plots <- diagnostic_plots(m1) + ggplot2::theme_minimal() names(plots) plots$y.index # Only the index plots diagnostic_plots(m1) |> subset("index")
blimp_obj
Plots the distribution of one variable across every saved imputation: observed values as filled bars, imputed values as outlined bars, and a density curve for each completed dataset.
distribution_plot(model, variable, bins = 30, discrete_max_unique = 5L)distribution_plot(model, variable, bins = 30, discrete_max_unique = 5L)
model |
a |
variable |
a character string naming one saved variable: a variable in the model,
a model-implied quantity (e.g., |
bins |
an integer. The target number of histogram bins for continuous variables; it also sets the smoothness of the density curves. Integer-valued variables always use a bin width of 1. |
discrete_max_unique |
an integer. A variable with this many or fewer distinct values in a completed dataset is treated as discrete (no density curves or Q-Q plot, integer axis ticks) even if it was not declared ORDINAL, NOMINAL, or COUNT. Declared variables and factor, character, and logical columns always are; categories are labeled by name. |
Variables are shown in one of three ways:
Observed (no missing values): filled bars.
Mixed (some values imputed): filled bars for observed values, outlined bars for imputed values from every imputation, and the percent imputed in the title.
Model-implied (residuals, latent variables, probabilities, and level-2 quantities): outlined bars. Level-2 quantities are reduced to one value per cluster first.
One density curve is drawn for each completed dataset (the observed values plus one
imputation's values), so the spread of the curves shows how much the imputations differ.
A variable with no imputed values gets one curve. The bandwidth equals the histogram's bin
width, so the curves and the bars show the same level of detail; bins changes both. The
curves are omitted for declared or effectively discrete variables. The vertical
(density) axis is not drawn; add ggplot2::scale_y_continuous(),
ggplot2::guides(y = "axis"), and ggplot2::labs(y = "Density") to show it.
Colors come from the plot theme: the observed-value bars use the theme's geom fill and the
imputed-value bars the data_color setting of blimp_style, or the first two colors of
the discrete fill and colour palettes when these are not set; the density curves use the
theme's accent. See ggplot2::element_geom. A fill or colour scale added to the plot
(e.g., scale_fill_manual(values = c(Observed = "grey70"))) takes precedence. The
transparency of the observed-value bars and of the density curves is set with blimp_style.
a ggplot2::ggplot plot
qq_plot, distribution_plots, residual_plot, blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Make some values of x missing set.seed(19723) mydata$x[sample(200, 50)] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Observed vs imputed values of x distribution_plot(m1, 'x') # Distribution of the residuals distribution_plot(m1, 'y.residual') + ggplot2::theme_minimal()# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Make some values of x missing set.seed(19723) mydata$x[sample(200, 50)] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Observed vs imputed values of x distribution_plot(m1, 'x') # Distribution of the residuals distribution_plot(m1, 'y.residual') + ggplot2::theme_minimal()
blimp_obj
Builds a distribution_plot for every plottable variable in a model, and a qq_plot
for every continuous one, as a named list of ggplot2::ggplot plots.
distribution_plots( model, selector, qq = TRUE, bins = 30, discrete_max_unique = 5L ) ## S3 method for class 'distribution_plots' print(x, ...) ## S3 method for class 'distribution_plots' x[i] ## S3 method for class 'distribution_plots' subset(x, pattern, ...) ## S3 method for class 'distribution_plots' e1 + e2 ## S3 method for class 'distribution_plots' e1 & e2distribution_plots( model, selector, qq = TRUE, bins = 30, discrete_max_unique = 5L ) ## S3 method for class 'distribution_plots' print(x, ...) ## S3 method for class 'distribution_plots' x[i] ## S3 method for class 'distribution_plots' subset(x, pattern, ...) ## S3 method for class 'distribution_plots' e1 + e2 ## S3 method for class 'distribution_plots' e1 & e2
model |
a |
selector |
an optional character vector of variable names. If missing, includes the variables in the model, the model-implied quantities (residuals, latent variables, probabilities, and Yeo-Johnson values), and level-2 quantities. |
qq |
a logical value. If |
bins |
an integer. The target number of histogram bins for continuous variables; it also sets the smoothness of the density curves. Integer-valued variables always use a bin width of 1. |
discrete_max_unique |
an integer. A variable with this many or fewer distinct values in a completed dataset is treated as discrete (no density curves or Q-Q plot, integer axis ticks) even if it was not declared ORDINAL, NOMINAL, or COUNT. Declared variables and factor, character, and logical columns always are; categories are labeled by name. |
x |
a |
... |
for |
i |
indices or names of the plots to keep. |
pattern |
a regular expression matched against the plot names. |
e1, e2
|
a |
Predicted values are not included by default; request them with selector.
A named list of plots with class distribution_plots, named by variable, with
Q-Q plots named <var>.qq. Printing it draws every plot. + and & add a ggplot2
component to every plot (the list must be on the left), and [ and subset() keep the
class. subset(x, pattern) keeps the plots whose names match pattern, e.g.
plots |> subset("qq").
distribution_plot, qq_plot, diagnostic_plots
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Make some values of x missing set.seed(19723) mydata$x[sample(200, 50)] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) plots <- distribution_plots(m1) names(plots) plots$x# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Make some values of x missing set.seed(19723) mydata$x[sample(200, 50)] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) plots <- distribution_plots(m1) names(plots) plots$x
Extracts the model estimates section from Blimp output.
estimates(object)estimates(object)
object |
A |
A blimp_out object containing model estimates
Returns a logical if blimp is detected by detect_blimp
has_blimp()has_blimp()
This function uses detect_blimp to determine if blimp is installed.
a logical
# Detect if system has blimp has_blimp()# Detect if system has blimp has_blimp()
blimp_obj
Index plots of the leverage and Cook's distance values Blimp computes for an outcome. Requires a version of Blimp that supports influence output.
influence_plot( model, variable, measure = c("leverage", "cooks"), max_labels = 10 )influence_plot( model, variable, measure = c("leverage", "cooks"), max_labels = 10 )
model |
a |
variable |
a character string naming one outcome. |
measure |
which values to plot: |
max_labels |
an integer. The maximum number of cases labeled in each panel. |
Blimp computes leverage and Cook's distance at every post burn-in iteration, from the
outcome's fixed-effects design as fitted, and averages them per case. Cook's distance uses
the pooled residual variance, so it is on the same scale across iterations. See
influence for the values.
Values are available for single-level continuous outcomes (including yjt() outcomes and
outcomes with a variance model) and ordinal probit outcomes.
Reference lines are drawn at and for leverage, where is the
number of columns in the design (the sum of the leverages), and at for Cook's
distance. Cases above or are labeled.
For a case whose outcome was imputed, Cook's distance reflects the uncertainty in its imputed value: it is the case's expected influence given its leverage.
To mark cases whose outcome was imputed, add scale_imputed.
Point transparency, reference lines, and labels are set with blimp_style.
a ggplot2::ggplot plot
residual_plot, diagnostic_plots, influence,
scale_imputed, blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) ## Not run: # Requires a version of Blimp that supports influence output m1 <- rblimp( 'y ~ x m x*m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000 ) # Leverage and Cook's distance influence_plot(m1, 'y') # Only Cook's distance influence_plot(m1, 'y', measure = 'cooks') # Mark cases whose outcome was imputed influence_plot(m1, 'y') + scale_imputed() ## End(Not run)# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) ## Not run: # Requires a version of Blimp that supports influence output m1 <- rblimp( 'y ~ x m x*m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000 ) # Leverage and Cook's distance influence_plot(m1, 'y') # Only Cook's distance influence_plot(m1, 'y', measure = 'cooks') # Mark cases whose outcome was imputed influence_plot(m1, 'y') + scale_imputed() ## End(Not run)
blimp_obj
Influence values from blimp_obj
## S4 method for signature 'blimp_obj' influence(model, ...)## S4 method for signature 'blimp_obj' influence(model, ...)
model |
A |
... |
Additional arguments (unused) |
Values are computed by Blimp and averaged over every post burn-in iteration. Only single-level continuous and ordinal probit outcomes are included.
A data frame with one row per case and three columns per eligible outcome:
<dv>.leverage (posterior-averaged leverage), <dv>.cooks (Cook's distance),
and <dv>.variance (posterior-averaged residual variance).
Downloads and installs Blimp into a user-writable directory managed by rblimp. This is an alternative to installing Blimp via the system installer from https://www.appliedmissingdata.com/blimp.
install_blimp(dir = NULL, force = FALSE, quiet = FALSE, linux_variant = NULL)install_blimp(dir = NULL, force = FALSE, quiet = FALSE, linux_variant = NULL)
dir |
Install directory. Defaults to a hidden, user-writable
per-OS location ( |
force |
Logical; overwrite an existing managed install, or proceed
even when a system installation of Blimp is detected. Default |
quiet |
Logical; suppress progress messages. Default |
linux_variant |
Optional character; |
The install directory location can be overridden globally via the
R_BLIMP_HOME environment variable.
Set R_BLIMP_PREVENT_INSTALL=true to disable install_blimp (intended for
locked-down environments).
Non-interactive R sessions require force = TRUE.
Path to the installed blimp executable, invisibly.
Calling install_blimp() contacts updates.blimpstats.com over HTTPS
to fetch the Blimp engine. Information may be collected as described
in the privacy policy.
See privacy policy: https://www.blimpstats.com/privacy.
## Not run: # Install Blimp to the default managed location install_blimp() # Install to a custom directory install_blimp(dir = "~/blimp-managed") # Force install on a Linux RHEL 8 system without auto-detection install_blimp(linux_variant = "rhel8") ## End(Not run)## Not run: # Install Blimp to the default managed location install_blimp() # Install to a custom directory install_blimp(dir = "~/blimp-managed") # Force install on a Linux RHEL 8 system without auto-detection install_blimp(linux_variant = "rhel8") ## End(Not run)
A 2-D analogue of jn_plot(). For a model with an outcome ~ focal x m1 x m2
interaction, the conditional slope of outcome on focal is a linear
surface over (m1, m2):
jn_map() recovers those four coefficients per MCMC draw from the
SIMPLE-evaluated points, evaluates them on a dense grid, and renders the
posterior median as a heatmap. A contour line marks the boundary of the
region where the ci posterior credible interval excludes zero – the 2-D
"region of significance".
The heatmap uses the theme's continuous fill palette (palette.fill.continuous)
with a slope of 0 at the palette's middle color, and otherwise a blue-white-red
scale. The contour's color, transparency, and width are set with blimp_style.
jn_map(formula, model, ci = 0.95, n_grid = 100, ...)jn_map(formula, model, ci = 0.95, n_grid = 100, ...)
formula |
an object of class |
model |
an |
ci |
a value between 0 and 1 specifying the credible-interval size for
the significance contour. Default |
n_grid |
integer length-1 or length-2. Number of grid points along
|
... |
currently unused. |
a ggplot2::ggplot plot. Attribute "grid" carries the per-cell
data frame (with lower, median, upper, sig columns).
jn_plot, simple_plot, at, join, blimp_style
## Not run: # Generate data with a three-way interaction mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.4*x + 0.3*m1 - 0.2*m2 + 0.5*x*m1 + 0.3*x*m2 + 0.2*m1*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 981273 ) # Fit the model -- SIMPLE must evaluate both moderators fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', mydata, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) # Default 2-D heatmap of the conditional slope of y on x jn_map(y ~ x | m1 + m2, fit) # Swap axes jn_map(y ~ x | m2 + m1, fit) # Inspect the underlying per-cell data head(attr(jn_map(y ~ x | m1 + m2, fit), 'grid')) ## End(Not run)## Not run: # Generate data with a three-way interaction mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.4*x + 0.3*m1 - 0.2*m2 + 0.5*x*m1 + 0.3*x*m2 + 0.2*m1*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 981273 ) # Fit the model -- SIMPLE must evaluate both moderators fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', mydata, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) # Default 2-D heatmap of the conditional slope of y on x jn_map(y ~ x | m1 + m2, fit) # Swap axes jn_map(y ~ x | m2 + m1, fit) # Inspect the underlying per-cell data head(attr(jn_map(y ~ x | m1 + m2, fit), 'grid')) ## End(Not run)
rblimp
Generates a Johnson-Neyman Plot based on the posterior summaries from the output of rblimp.
jn_plot(formula, model, ci = 0.95, ...)jn_plot(formula, model, ci = 0.95, ...)
formula |
an object of class |
model |
an |
ci |
a value between 0 and 1 specifying the credible interval size |
... |
passed bounds search algorithm. See |
To change colors use ggplot2's scale system; the shaded regions use the fill scale. See
ggplot2::aes_colour_fill_alpha for more information about setting a manual set of colors.
The shaded regions use the fill values FALSE (0 is within the interval) and TRUE
(0 is outside the interval), e.g., scale_fill_manual(values = c("FALSE" = "grey80", "TRUE" = "grey40")).
The band transparency and the boundary lines are set with blimp_style.
When the model contains a SIMPLE command that evaluates the focal predictor at
multiple values of the formula moderator (e.g., 'x | m @ quantile'), the
conditional slope is reconstructed from the SIMPLE slope draws via a
per-iteration linear fit across the evaluated points. If the same SIMPLE
command also holds one or two additional moderators at multiple values
(e.g., 'x | m @ quantile and z @ sd'), the plot is faceted by those
additional moderators. When SIMPLE has no relevant rows, jn_plot falls
back to building the conditional slope directly from the model's fixed-effect
interaction parameter (the original behavior).
PARAM) effectsA SIMPLE command whose focal is an expression of labeled model parameters
(e.g. simple = 'b4 + b7*mod | mod') produces a compound-parameter
conditional effect: a single generated quantity per moderator value, with no
intercept. Because these have no conditional regression line, they are shown
only as a Johnson-Neyman region of significance – simple_plot and
jn_map do not apply.
Reference such an effect by putting its focal-expression label on the
left-hand side of the formula, with the moderator on the right (no outcome,
no |). The label may be written unquoted or quoted:
jn_plot(b4 + b7*mod ~ mod, model) # unquoted
jn_plot("b4 + b7*mod" ~ mod, model) # quoted (equivalent)
The label is matched to the SIMPLE output ignoring whitespace and case, so
the two forms above are the same. (Absence of | on the right-hand side is
what selects this path.) Additional moderators may be pinned with at,
exactly as in the standard path. The generated effect is linear in the
moderator, so its value at each evaluated point is used to reconstruct the
effect (and its region of significance) exactly.
a ggplot2::ggplot plot. The bounding values are saved in the attribute 'bounds'.
jn_plot_func, jn_map, simple_plot, simple_effects, at, join,
blimp_style
## Not run: # ---- Basic single-moderator example ---- mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) jn_plot(y ~ x | m, m1) # Custom significance-region fill ( jn_plot(y ~ x | m, m1) + ggplot2::scale_fill_manual( values = c(`FALSE` = '#ca0020', `TRUE` = '#0571b0') ) ) # ---- Two-moderator fit: first mod = x-axis, second auto-faceted ---- three_way <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x*m1 + 0.3*x*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 2024 ) fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', three_way, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) jn_plot(y ~ x | m1 + m2, fit) # Pin one moderator via `at()` jn_plot(y ~ x | m1 + at(m2 = "0"), fit) # Restrict to a subset of SIMPLE values jn_plot(y ~ x | m1 + at(m2 = c("-1 SD", "+1 SD")), fit) # Per-facet boundary x-values are also exposed as an attribute attr(jn_plot(y ~ x | m1 + m2, fit), "bounds") # ---- Compound-parameter (PARAM) conditional effect ---- cp <- rblimp( 'y ~ x@b1 m x*m@b2', mydata, center = ~ m, simple = 'b1 + b2*m | m', seed = 10972, burn = 1000, iter = 1000 ) # Focal-expression label on the left, moderator on the right, no `|`. jn_plot(b1 + b2*m ~ m, cp) # unquoted jn_plot("b1 + b2*m" ~ m, cp) # or quoted ## End(Not run)## Not run: # ---- Basic single-moderator example ---- mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) jn_plot(y ~ x | m, m1) # Custom significance-region fill ( jn_plot(y ~ x | m, m1) + ggplot2::scale_fill_manual( values = c(`FALSE` = '#ca0020', `TRUE` = '#0571b0') ) ) # ---- Two-moderator fit: first mod = x-axis, second auto-faceted ---- three_way <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x*m1 + 0.3*x*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 2024 ) fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', three_way, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) jn_plot(y ~ x | m1 + m2, fit) # Pin one moderator via `at()` jn_plot(y ~ x | m1 + at(m2 = "0"), fit) # Restrict to a subset of SIMPLE values jn_plot(y ~ x | m1 + at(m2 = c("-1 SD", "+1 SD")), fit) # Per-facet boundary x-values are also exposed as an attribute attr(jn_plot(y ~ x | m1 + m2, fit), "bounds") # ---- Compound-parameter (PARAM) conditional effect ---- cp <- rblimp( 'y ~ x@b1 m x*m@b2', mydata, center = ~ m, simple = 'b1 + b2*m | m', seed = 10972, burn = 1000, iter = 1000 ) # Focal-expression label on the left, moderator on the right, no `|`. jn_plot(b1 + b2*m ~ m, cp) # unquoted jn_plot("b1 + b2*m" ~ m, cp) # or quoted ## End(Not run)
Generates a Johnson-Neyman Plot using a function to produce the conditional effect
jn_plot_func(func, xrange, ci = 0.95, ...)jn_plot_func(func, xrange, ci = 0.95, ...)
func |
a |
xrange |
a |
ci |
a value between 0 and 1 specifying the credible interval size |
... |
values passed to internal boundary search algorithm. See Details below. |
To change colors use ggplot2's scale system; the shaded regions use the fill scale. See
ggplot2::aes_colour_fill_alpha for more information about setting a manual set of colors.
The shaded regions use the fill values FALSE (0 is within the interval) and TRUE
(0 is outside the interval), e.g., scale_fill_manual(values = c("FALSE" = "grey80", "TRUE" = "grey40")).
The band transparency and the boundary lines are set with blimp_style.
For ..., the arguments are passed to the internal boundary search algorithm.
This algorithm uses an initial grid search to locate boundaries based on the range
and then a binary search to refine the estimates.
The following arguments are available:
Number of points in the initial coarse grid search used to locate approximate boundary positions. Higher values improve detection of closely-spaced boundaries but increase computation time. Default is 1000.
Tolerance for binary search refinement. The algorithm refines each boundary until the interval width is smaller than this value. Smaller values give higher precision but require more function evaluations. Default is 1e-12.
Maximum number of iterations for binary search refinement per boundary. Prevents infinite loops if tolerance cannot be achieved. Default is 100.
Logical indicating whether to perform additional refinement in regions where boundaries are detected to be closely spaced. When TRUE, uses a finer grid to resolve boundaries that may be missed by the initial coarse grid. Default is TRUE.
a ggplot2::ggplot plot. The bounding values are saved in the attribute 'boundaries'.
compute_condeff(), blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.5*x2 + m + 0.2*x1*x2 + 0.3*x2*m + 0.1*x1*m + 0.7*x1*x2*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x1 x2 m x1*x2 x1*m x2*m x1*x2*m', mydata, center = ~ m, seed = 10972, burn = 1000, iter = 1000 ) # Get parameter values params <- m1 |> as.matrix() # Generate Plot ( jn_plot_func( compute_condeff(params[,6], params[,9]), xrange = c(-3, 3) ) + ggplot2::labs( title = 'Johnson-Neyman Plot for `x1` * `x2` Moderated by `x2`', subtitle = 'Shading shows whether 0 is within the 95% interval', y = 'y ~ x1 * x2', x = 'm' ) + ggplot2::theme_minimal() )# Generate Data mydata <- rblimp_sim( c( 'x1 ~ normal(0, 1)', 'x2 ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x1 + 0.5*x2 + m + 0.2*x1*x2 + 0.3*x2*m + 0.1*x1*m + 0.7*x1*x2*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x1 x2 m x1*x2 x1*m x2*m x1*x2*m', mydata, center = ~ m, seed = 10972, burn = 1000, iter = 1000 ) # Get parameter values params <- m1 |> as.matrix() # Generate Plot ( jn_plot_func( compute_condeff(params[,6], params[,9]), xrange = c(-3, 3) ) + ggplot2::labs( title = 'Johnson-Neyman Plot for `x1` * `x2` Moderated by `x2`', subtitle = 'Shading shows whether 0 is within the 95% interval', y = 'y ~ x1 * x2', x = 'm' ) + ggplot2::theme_minimal() )
Used inside simple_plot and jn_plot formulas to treat a set of
SIMPLE moderators as a single conceptual moderator. Each row's color/legend
label combines every component's "name @ value" so that, e.g., the dummy
codes of a nominal predictor render as one set of colored lines instead of
a sparse facet grid.
join(...)join(...)
... |
bare moderator names (at least two) to bundle together. |
Only the first bare term on the right-hand side of | may use join(...)
(that is, the color / x-axis position). Facet positions must remain plain
moderator names or at(...) calls.
Calling join() outside a formula raises an error; it only has
meaning inside simple_plot() / jn_plot() formulas.
simple_plot, jn_plot, jn_map, at
## Not run: # Nominal predictor with dummy codes -- bundle them as one moderator simple_plot(y ~ x | join(group.1, group.2), model) # Combine with `at()` to pin an unrelated moderator simple_plot(y ~ x | join(group.1, group.2) + at(z = "0"), model) # In a 4-way fit, collapse the two facet moderators so the bound # annotation goes back into each strip of the JN plot jn_plot(y ~ x | m1 + join(m2, m3), four_way_model) ## End(Not run)## Not run: # Nominal predictor with dummy codes -- bundle them as one moderator simple_plot(y ~ x | join(group.1, group.2), model) # Combine with `at()` to pin an unrelated moderator simple_plot(y ~ x | join(group.1, group.2) + at(z = "0"), model) # In a 4-way fit, collapse the two facet moderators so the bound # annotation goes back into each strip of the JN plot jn_plot(y ~ x | m1 + join(m2, m3), four_way_model) ## End(Not run)
Generates an APA-formatted HTML table of model estimates that opens in the RStudio Viewer. Provides publication-ready tables with proper formatting for Bayesian model results.
model_table( object, selector, digits = 3, caption = NULL, show_chains = TRUE, show_neff = FALSE )model_table( object, selector, digits = 3, caption = NULL, show_chains = TRUE, show_neff = FALSE )
object |
A |
selector |
Optional character string specifying variable name or block to display. If missing, creates separate tables for each variable. |
digits |
Integer specifying number of decimal places. Default is 3. |
caption |
Optional character string for table caption. |
show_chains |
Logical indicating whether to show chain information. Default is TRUE. |
show_neff |
Logical indicating whether to show effective sample size. Default is FALSE. |
The function creates APA-style tables with the following features:
Proper coefficient formatting with confidence intervals
Organized sections for different parameter types
Publication-ready styling
Responsive design for different screen sizes
Tables are displayed in the RStudio Viewer pane and can be exported or copied.
Invisibly returns the HTML content. Primary purpose is displaying in Viewer.
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 10972 ) # Fit model model <- rblimp( 'y ~ x', mydata, seed = 10972, burn = 1000, iter = 1000 ) # Create APA table for all variables model_table(model) # Create table for specific variable model_table(model, "y") # Customize formatting model_table(model, digits = 2, caption = "Bayesian Model Results")# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 10972 ) # Fit model model <- rblimp( 'y ~ x', mydata, seed = 10972, burn = 1000, iter = 1000 ) # Create APA table for all variables model_table(model) # Create table for specific variable model_table(model, "y") # Customize formatting model_table(model, digits = 2, caption = "Bayesian Model Results")
Extracts the model fit section from Blimp output.
modelfit(object)modelfit(object)
object |
A |
A blimp_out object containing model fit information
Extracts the model information section from Blimp output.
modelinfo(object)modelinfo(object)
object |
A |
A blimp_out object containing model information
blimp_obj objectReturn variable names from blimp_obj object
## S4 method for signature 'blimp_obj' names(x)## S4 method for signature 'blimp_obj' names(x)
x |
A |
A character vector of variable names from the average imputation data.
Extracts the raw Blimp output text from a blimp_obj.
output(object)output(object)
object |
A |
A blimp_out object containing the raw Blimp output text
Generates ggplot2::ggplot plots using ggplot2::geom_density based on the output from rblimp
posterior_plot(model, selector, ...)posterior_plot(model, selector, ...)
model |
an |
selector |
a name of a variable, a name of a parameter, a number of a parameter, or a combination of any of them. If left empty, a plot of all parameters will be returned. See Examples. |
... |
arguments passed to internally called |
To change colors use ggplot2's scale system. Both fill and color are used. See
ggplot2::aes_colour_fill_alpha for more information about setting a manual set of colors.
The fill transparency is set with blimp_style. The vertical (density) axis is not drawn;
add ggplot2::scale_y_continuous(), ggplot2::guides(y = "axis"), and
ggplot2::labs(y = "Density") to show it.
a ggplot2::ggplot plot
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( c( 'y ~ x m', 'x ~~ m' ), mydata, seed = 10972, burn = 1000, iter = 1000 ) # Generate plot of all parameters with `y` posterior_plot(m1, 'y') + ggplot2::theme_minimal() # Generate plot of all parameters posterior_plot(m1) + ggplot2::theme_minimal() # Generate plot of all parameters for `y` and `x` posterior_plot(m1, c('x', 'y')) + ggplot2::theme_minimal() # Generate Plot of Parameter 5 posterior_plot(m1, 5) + ggplot2::theme_minimal() # Generate plot of `x residual variance` posterior_plot(m1, 'x residual variance') + ggplot2::theme_minimal() # Generate plot of Parameters 7 and 9 posterior_plot(m1, c(7, 9)) + ggplot2::theme_minimal()# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( c( 'y ~ x m', 'x ~~ m' ), mydata, seed = 10972, burn = 1000, iter = 1000 ) # Generate plot of all parameters with `y` posterior_plot(m1, 'y') + ggplot2::theme_minimal() # Generate plot of all parameters posterior_plot(m1) + ggplot2::theme_minimal() # Generate plot of all parameters for `y` and `x` posterior_plot(m1, c('x', 'y')) + ggplot2::theme_minimal() # Generate Plot of Parameter 5 posterior_plot(m1, 5) + ggplot2::theme_minimal() # Generate plot of `x residual variance` posterior_plot(m1, 'x residual variance') + ggplot2::theme_minimal() # Generate plot of Parameters 7 and 9 posterior_plot(m1, c(7, 9)) + ggplot2::theme_minimal()
blimp_obj
Predicted scores from blimp_obj
## S4 method for signature 'blimp_obj' predict(object, ...)## S4 method for signature 'blimp_obj' predict(object, ...)
object |
A |
... |
Additional arguments (unused) |
A list of data frames, one per imputation, each containing the predicted values and probability columns from the model.
blimp_simple_effects
Print method for blimp_simple_effects
## S3 method for class 'blimp_simple_effects' print(x, digits = attr(x, "digits"), ...)## S3 method for class 'blimp_simple_effects' print(x, digits = attr(x, "digits"), ...)
x |
A |
digits |
Integer number of decimal places. Defaults to the value stored
on |
... |
Unused. |
x, invisibly.
Prints the standardized solutions matrix returned by standardized() as an
aligned table, rounded for readability. The underlying object retains full
precision; only the displayed values are rounded.
## S3 method for class 'blimp_std' print(x, digits = 3, ...)## S3 method for class 'blimp_std' print(x, digits = 3, ...)
x |
A |
digits |
Integer specifying the number of decimal places to display. Default is 3. |
... |
Additional arguments passed to |
The blimp_std object x (invisibly). Called for its side effect of
printing the rounded, aligned table to the console.
blimp_syntax
Print blimp_syntax
## S3 method for class 'blimp_syntax' print(x, ...)## S3 method for class 'blimp_syntax' print(x, ...)
x |
A |
... |
Additional arguments (unused) |
The blimp_syntax object (invisibly). Called for its side effect
of printing the formatted syntax to the console.
blimp_obj
Plots the predicted probability of each category of an ordinal or nominal outcome against a predictor, using every saved imputation.
probability_plot(model, variable, x, discrete_max_unique = 10L)probability_plot(model, variable, x, discrete_max_unique = 10L)
model |
a |
variable |
a character string naming an ordinal or nominal outcome. |
x |
a character string naming one predictor of |
discrete_max_unique |
an integer. A predictor with this many or fewer distinct values in a completed dataset gets category means instead of loess curves, even if it was not declared ORDINAL, NOMINAL, or COUNT. Declared predictors and factor, character, and logical columns always do. |
Every saved category probability is plotted: all categories for an ordinal outcome and the
non-reference categories for a nominal outcome. Points stack all imputations. For a
continuous predictor, each category gets a loess curve fit within each imputation and
averaged; for a discrete predictor (see discrete_max_unique), each category gets its mean
probability at each level. Factor and character predictors are labeled by category name.
With curves, the subtitle gives the number of imputations averaged, as in residual_plot.
Categories are distinguished by colour, point shape, and line type, so the plot also reads
in greyscale. These come from the theme's discrete palettes (palette.colour.discrete,
palette.shape.discrete, and palette.linetype.discrete); without shape or line type
palettes, a fixed set of seven of each is used. Point transparency and the category-mean
markers are set with blimp_style.
a ggplot2::ggplot plot
residual_plot, diagnostic_plots, blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'ystar ~ normal(0.7*x, 1)' ), n = 200, seed = 981273 ) mydata$y <- cut(mydata$ystar, c(-Inf, -0.5, 0.5, Inf), labels = FALSE) # Run Rblimp m1 <- rblimp('y ~ x', mydata, ordinal = 'y', nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Predicted probability across x probability_plot(m1, 'y', 'x')# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'ystar ~ normal(0.7*x, 1)' ), n = 200, seed = 981273 ) mydata$y <- cut(mydata$ystar, c(-Inf, -0.5, 0.5, Inf), labels = FALSE) # Run Rblimp m1 <- rblimp('y ~ x', mydata, ordinal = 'y', nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Predicted probability across x probability_plot(m1, 'y', 'x')
Extracts the PSR convergence diagnostic section from Blimp output.
psr(object)psr(object)
object |
A |
A blimp_out object containing PSR output
blimp_obj
Plots the standardized values of one variable against standard normal quantiles, one set of points per completed dataset, overlaid.
qq_plot(model, variable, discrete_max_unique = 5L)qq_plot(model, variable, discrete_max_unique = 5L)
model |
a |
variable |
a character string naming one saved variable: a variable in the model,
a model-implied quantity (e.g., |
discrete_max_unique |
an integer. A variable with this many or fewer distinct values in a completed dataset is treated as discrete (no density curves or Q-Q plot, integer axis ticks) even if it was not declared ORDINAL, NOMINAL, or COUNT. Declared variables and factor, character, and logical columns always are; categories are labeled by name. |
Each completed dataset (the observed values plus one imputation's imputed values; level-2 quantities reduced to one value per cluster) is sorted and plotted against the normal quantiles for its size, so every case counts once in each dataset. Points are matched by rank, not by case. Values are standardized by their mean and the pooled within-imputation standard deviation, and plotted on equal axes with a 45-degree reference line. A variable with no imputed values gives one set of points.
A Q-Q plot is not drawn for predicted probabilities (bounded in [0, 1]), for the residuals of ordinal, nominal, or count outcomes (latent-response residuals), or for discrete variables; requesting one gives an error explaining why.
Point transparency and the reference line are set with blimp_style.
a ggplot2::ggplot plot
distribution_plot, distribution_plots, blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Normality of the residuals qq_plot(m1, 'y.residual')# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 200, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # Normality of the residuals qq_plot(m1, 'y.residual')
rblimp will generate the input, run the script, and load most the saved data into an R object. rblimp_fcs
is used to specify the FCS command in Blimp. rblimp_syntax will generate the Blimp syntax file only.
rblimp( model, data, burn = 10000, iter = 10000, seed, thin, nimps, latent, randomeffect, parameters, clusterid, timeid, weight, ordinal, nominal, count, center, chains, simple, waldtest, options, transform, dropout, filter, fixed, output, tmpfolder, add_save = TRUE, print_output = TRUE, nopowershell = FALSE ) rblimp_fcs( variables, data, burn = 10000, iter = 10000, seed, thin, nimps, clusterid, ordinal, nominal, chains, options, transform, fixed, output, tmpfolder, add_save = TRUE, print_output = TRUE, nopowershell = FALSE ) rblimp_syntax( model, data, burn, iter, seed, thin, nimps, latent, randomeffect, parameters, clusterid, timeid, weight, ordinal, nominal, count, transform, dropout, filter, fixed, center, chains, simple, waldtest, options, save, output )rblimp( model, data, burn = 10000, iter = 10000, seed, thin, nimps, latent, randomeffect, parameters, clusterid, timeid, weight, ordinal, nominal, count, center, chains, simple, waldtest, options, transform, dropout, filter, fixed, output, tmpfolder, add_save = TRUE, print_output = TRUE, nopowershell = FALSE ) rblimp_fcs( variables, data, burn = 10000, iter = 10000, seed, thin, nimps, clusterid, ordinal, nominal, chains, options, transform, fixed, output, tmpfolder, add_save = TRUE, print_output = TRUE, nopowershell = FALSE ) rblimp_syntax( model, data, burn, iter, seed, thin, nimps, latent, randomeffect, parameters, clusterid, timeid, weight, ordinal, nominal, count, transform, dropout, filter, fixed, center, chains, simple, waldtest, options, save, output )
model |
a character string or vector/list of character strings. Specifies Blimp's MODEL command. See details. |
data |
a |
burn |
an integer. The number of burn-in iterations to be run |
iter |
an integer. The number of post burn-in iterations to be run |
seed |
a positive integer. The seeding value for Blimp's pseudo random number generator |
thin |
an integer. The thinning interval for imputations only. |
nimps |
an integer. The number of imputations to save. |
latent |
a character string, formula, or vector/list of character strings. Specifies Blimp's LATENT command. See details. |
randomeffect |
a character string or vector/list of character strings. Specifies Blimp's RANDOMEFFECTS command. |
parameters |
a character string or vector/list of character strings. Specifies Blimp's MODEL command. See details. |
clusterid |
a character string, formula, or vector/list of character strings. Specifies Blimp's CLUSTERID command. See details. |
timeid |
a character string, formula, or vector/list of character strings. Specifies Blimp's TIMEID command. See details. |
weight |
a character string, formula, or vector/list of character strings. Specifies Blimp's WEIGHT command. See details. |
ordinal |
a character string, formula, or vector/list of character strings. Specifies Blimp's ORDINAL command. See details. |
nominal |
a character string, formula, or vector/list of character strings. Specifies Blimp's NOMINAL command. See details. |
count |
a character string, formula, or vector/list of character strings. Specifies Blimp's COUNT command. See details. |
center |
a character string, formula, or vector/list of character strings. Specifies Blimp's CENTER command. See details. |
chains |
an integer, character string, or vector/list of character strings. Specifies Blimp's CHAINS command. |
simple |
a character string or vector/list of character strings. Specifies Blimp's SIMPLE command. See details. |
waldtest |
a character string or vector/list of character strings. Specifies Blimp's WALDTEST command. See details. |
options |
a character string or vector/list of character strings. Specifies Blimp's OPTIONS command. |
transform |
a character string or vector/list of character strings. Specifies Blimp's TRANSFORM command. |
dropout |
a character string, formula, or vector/list of character strings. Specifies Blimp's DROPOUT command. See details. |
filter |
a character string. Specifies Blimp's FILTER command. |
fixed |
a character string, formula, or vector/list of character strings. Specifies Blimp's FIXED command. See details. |
output |
a character string or vector/list of character strings. Specifies Blimp's OUTPUT command |
tmpfolder |
a character string. If specified |
add_save |
a single logical value or a list of logical values.
If |
print_output |
The type of output printed to the console.
|
nopowershell |
Windows only. Uses cmd.exe with some limited functions (instead of powershell). |
variables |
list of variables to be included in FCS procedure |
save |
Specify SAVE command for blimp syntax |
The above functions require knowledge of specifying Blimp commands. Blimp's syntax commands are documented in the Blimp User Manual
By default, these commands can be inputted as character strings that will be used to generate the syntax.
For multiple lined commands, you can wrap multiple strings into a character vector or a list.
The appropriate semicolons will be specified, so they are not required in any character strings.
If specifying a character vector or a list for the model, providing names to each element
will be used as blocks in Blimp's model syntax. Similarly, specifying named elements can be used
for the center command to specify if you would like centering within a cluster or
grand mean centering. This also works for the latent input when requesting latent
variables at a specific cluster identifier.
See the Blimp User Manual
for more details about types of centering and specifying latent variables.
In addition, R's formula syntax can be used to specify lists of variables
in place of character strings. For example, specifying the CLUSTERID command with
the variable id can be specified as ~ id as opposed to a character string.
Similarly, + can be used to specify multiple variables. For example, to specify
two variables as ordinal the formula would be: ~ x1 + x2. Finally, this can also be
used to specify centering and latent variables. For example, to center x1 and x2
within cluster we can specify: cwc ~ x1 + x2.
Running rblimp will also check if blimp is up to date.
See details in rblimp_source for more information.
SIMULATE() for creating simulated data to fit within rblimp()
rblimp_sim() for generating simulated datasets
# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit SEM Model model <- rblimp( list( structure = 'y ~ f', measurement = 'f -> x1:x5' ), mydata, seed = 3927, latent = ~ f ) # View results summary(model)# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit SEM Model model <- rblimp( list( structure = 'y ~ f', measurement = 'f -> x1:x5' ), mydata, seed = 3927, latent = ~ f ) # View results summary(model)
A guide to installing and configuring Blimp software for use with rblimp.
rblimp requires the Blimp engine. The simplest way to install it is from R:
install_blimp()
This downloads the latest Blimp engine into a user-writable directory:
macOS: ~/.blimp/
Windows: %LOCALAPPDATA%/Blimp/
Linux: ~/.blimp/
Override the location with the R_BLIMP_HOME environment variable.
Use uninstall_blimp to remove it.
If you'd rather use Blimp's standalone system installer (downloaded from https://www.appliedmissingdata.com/blimp), rblimp will auto-detect it and use it instead.
If autodetection fails, set the path manually with set_blimp or the
R_BLIMP environment variable.
Privacy: Downloads are recorded for usage statistics.
See privacy policy: https://www.blimpstats.com/privacy.
By default, rblimp automatically checks for Blimp updates when you run models. This ensures you're using the latest version with bug fixes and improvements.
To disable automatic update checks:
# Disable for current session options(check_blimp_update = FALSE) # Or add to .Rprofile for permanent setting: # options(check_blimp_update = FALSE) # Or set environment variable (useful for CI / sysadmin contexts): # R_BLIMP_NO_UPDATE_CHECK=true
You can manually update Blimp at any time:
update_blimp()
For managed installs, this re-downloads the latest Blimp engine. For system installs, this launches the Blimp Updater application.
Model Fitting:
rblimp - Fit Bayesian models
rblimp_fcs - Fully Conditional Specification imputation
rblimp_syntax - Generate Blimp syntax
rblimp_source - Run existing Blimp syntax files
Simulation:
rblimp_sim - Generate simulated datasets
SIMULATE - Create simulation specifications
Output & Analysis:
summary - Model summary
estimates - Extract parameter estimates
describe - Descriptive statistics
psr - Potential Scale Reduction values
output - Raw Blimp output
standardized - Extract standardized parameters only
compare - Compare models
simple_effects - Conditional effects from the SIMPLE command
Visualization (see rblimp_plots for styling and saving plots):
trace_plot - MCMC trace plots
posterior_plot - Posterior density plots
residual_plot - Residual diagnostics
influence_plot - Leverage and Cook's distance
probability_plot - Predicted category probabilities
distribution_plot - Observed and imputed distributions
qq_plot - Normal Q-Q plots
diagnostic_plots - Every applicable diagnostic plot
distribution_plots - Every applicable distribution plot
theme_blimp - A ready-made theme for rblimp plots
blimp_style - Theme settings for rblimp plots
scale_imputed - Mark imputed values in diagnostic plots
jn_plot - Johnson-Neyman plots
jn_plot_func - Johnson-Neyman plots for a function of the parameters
jn_map - Johnson-Neyman map for a three-way interaction
simple_plot - Simple slopes plots
model_table - Publication tables
Utilities:
by_group - Grouped analysis
as.mitml - Convert to mitml format
names - Obtain imputation variable names
with - Evaluate across imputations
write.blimp - Write results to files
Setup & Configuration:
install_blimp - Install Blimp into a managed directory
uninstall_blimp - Remove the managed install
detect_blimp - Detect Blimp installation
set_blimp - Set path to Blimp executable
has_blimp - Check if Blimp is available
update_blimp - Update Blimp installation
GitHub repository: https://github.com/blimp-stats/rblimp
Example files: https://github.com/blimp-stats/rblimp-examples
Blimp User Guide: https://docs.blimpstats.com
Report issues: https://github.com/blimp-stats/rblimp/issues
Every rblimp plot is a ggplot2::ggplot, so you style and save it as you would any
ggplot. This page shows the parts specific to rblimp, using a plot such as
p <- residual_plot(model, 'y', x = 'x'). The plotting functions themselves are listed
in rblimp_getting_started.
rblimp's plots draw with the colors, line widths, point sizes, and fonts of the plot's
ggplot2 theme, so adding a theme restyles the whole plot. Use any ggplot2 theme, or
theme_blimp for rblimp's ready-made look, and set one with
ggplot2::theme_set to use it for every plot in the session. Colors and sizes come
from the theme's geom settings: points and lines use the ink color and curves the
accent color.
p + theme_blimp(base_size = 14) p + ggplot2::theme(geom = ggplot2::element_geom(ink = "grey30", accent = "black")) old <- ggplot2::theme_set(theme_blimp()) # every plot from here on ggplot2::theme_set(old) # back to the previous theme
A few things have no ggplot2 theme setting: the transparency of points and bands, the
data color (which theme_blimp uses for its points), category-mean markers,
reference lines, case labels, and Johnson-Neyman boundaries. Set them with
blimp_style. To show which cases had their outcome imputed, add scale_imputed
(or scale_imputed_manual to pick the colors). Titles and labels work as in any
ggplot; for a figure, you might drop the title and the "Averaged over M imputations"
subtitle.
p + blimp_style(point_alpha = 0.1, reference_color = "red") p + scale_imputed() p + ggplot2::labs(title = NULL, subtitle = NULL)
Keep a style in a list and add it like a single component. diagnostic_plots and
distribution_plots return named lists of plots, and + adds to every plot in the
list; pick plots by name, or keep the ones whose names match a pattern with subset().
my_style <- list(theme_blimp(base_size = 14), blimp_style(point_alpha = 0.1)) p + my_style plots <- diagnostic_plots(model) + my_style subset(plots, "index")
Save a plot as an image with ggplot2::ggsave, or a whole list with a loop. To keep
a plot to draw or change later, use saveRDS; it keeps only the data it draws, not
the model.
ggplot2::ggsave("residuals.png", p + my_style, width = 6, height = 4, dpi = 300)
for (name in names(plots)) {
ggplot2::ggsave(paste0(name, ".png"), plots[[name]], width = 6, height = 4, dpi = 300)
}
# A model with some missing outcome values mydata <- rblimp_sim( c('x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)'), n = 100, seed = 981273 ) mydata$y[1:20] <- NA model <- rblimp('y ~ x', mydata, nimps = 20, seed = 10972, burn = 1000, iter = 1000) p <- residual_plot(model, 'y', x = 'x') # A theme, rblimp's settings, and the imputed values marked p + theme_blimp() + blimp_style(point_alpha = 0.2) + scale_imputed() # One style for a whole list of plots my_style <- list(theme_blimp(base_size = 14), blimp_style(point_alpha = 0.1)) plots <- diagnostic_plots(model) + my_style subset(plots, "index") # Save a plot ggplot2::ggsave(file.path(tempdir(), "residuals.png"), p + my_style, width = 6, height = 4)# A model with some missing outcome values mydata <- rblimp_sim( c('x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)'), n = 100, seed = 981273 ) mydata$y[1:20] <- NA model <- rblimp('y ~ x', mydata, nimps = 20, seed = 10972, burn = 1000, iter = 1000) p <- residual_plot(model, 'y', x = 'x') # A theme, rblimp's settings, and the imputed values marked p + theme_blimp() + blimp_style(point_alpha = 0.2) + scale_imputed() # One style for a whole list of plots my_style <- list(theme_blimp(base_size = 14), blimp_style(point_alpha = 0.1)) plots <- diagnostic_plots(model) + my_style subset(plots, "index") # Save a plot ggplot2::ggsave(file.path(tempdir(), "residuals.png"), p + my_style, width = 6, height = 4)
Generate simulated datasets using Blimp's SIMULATE command. Supports both single-level and multilevel data generation.
rblimp_sim( model, n, seed, define = NULL, variables = NULL, tmpfolder, nopowershell = FALSE )rblimp_sim( model, n, seed, define = NULL, variables = NULL, tmpfolder, nopowershell = FALSE )
model |
Character string or vector specifying data generation equations.
Can be specified as a vector: |
n |
Sample size. For single-level: integer (e.g., |
seed |
Random seed for reproducibility. |
define |
Character vector or string of parameter definitions (optional).
Can be |
variables |
Formula or character string specifying which variables to save (optional). If not specified, all variables from the model are saved. |
tmpfolder |
Character string. Temporary folder path. If not specified, creates one with |
nopowershell |
Windows only. Uses cmd.exe instead of powershell. |
A data.frame with simulated data. The returned object has two attributes:
The Blimp syntax used for simulation (blimp_syntax object)
The raw Blimp output (blimp_out object)
Access these with attr(result, "syntax") and attr(result, "output").
SIMULATE() for creating a simulation specification to use with rblimp()
# Simple regression: y = 10 + 0.5*x + error dat <- rblimp_sim( model = c( "x = normal(0, 1)", "y = normal(10 + x*0.5, 1)" ), n = 1000, seed = 10972 ) # Same thing with full quoted syntax dat <- rblimp_sim( model = "x = normal(0, 1); y = normal(10 + x*0.5, 1);", n = 1000, seed = 10972 ) # With parameter definitions dat <- rblimp_sim( model = c( "x = normal(0, 1)", "y = normal(b0 + b1*x, s2e)" ), n = 1000, define = c("b0 = 10", "b1 = 0.5", "s2e = 1"), seed = 10972 ) # Multilevel model dat <- rblimp_sim( model = list( schools = c( "z = normal(0, 1)", "u0 = normal(10 + z*-0.5, 1.0)" ), students = c( "x = normal(0, 1)", "y = normal(u0 + x*0.5, 1)" ) ), n = list(students = 1000, schools = 100), seed = 198723 ) # Access syntax and output syntax <- attr(dat, "syntax") print(syntax) output <- attr(dat, "output") print(output)# Simple regression: y = 10 + 0.5*x + error dat <- rblimp_sim( model = c( "x = normal(0, 1)", "y = normal(10 + x*0.5, 1)" ), n = 1000, seed = 10972 ) # Same thing with full quoted syntax dat <- rblimp_sim( model = "x = normal(0, 1); y = normal(10 + x*0.5, 1);", n = 1000, seed = 10972 ) # With parameter definitions dat <- rblimp_sim( model = c( "x = normal(0, 1)", "y = normal(b0 + b1*x, s2e)" ), n = 1000, define = c("b0 = 10", "b1 = 0.5", "s2e = 1"), seed = 10972 ) # Multilevel model dat <- rblimp_sim( model = list( schools = c( "z = normal(0, 1)", "u0 = normal(10 + z*-0.5, 1.0)" ), students = c( "x = normal(0, 1)", "y = normal(u0 + x*0.5, 1)" ) ), n = list(students = 1000, schools = 100), seed = 198723 ) # Access syntax and output syntax <- attr(dat, "syntax") print(syntax) output <- attr(dat, "output") print(output)
This function runs 'imp' file with Blimp and captures the output only.
rblimp_source(file, plots = FALSE, output = TRUE, nopowershell = FALSE)rblimp_source(file, plots = FALSE, output = TRUE, nopowershell = FALSE)
file |
a character string to the 'imp' file's location |
plots |
a logical. Setting to |
output |
The type of output printed to the console.
|
nopowershell |
Windows only. Uses cmd.exe with some limited functions (instead of powershell). |
If the installed version of Blimp supports it, Blimp also writes influence.csv (leverage,
Cook's distance, and residual variance) into the folder containing file.
Running rblimp_source will also run a check to see if Blimp is up to date.
If Blimp is not up to date, it will prompt the user if it would like to update or not.
This check will only be performed on the first run in a session and then every ten hours.
This behavior can be disabled by setting the check_blimp_update option to FALSE using options,
or by setting the R_BLIMP_NO_UPDATE_CHECK environment variable to "true".
This check is not performed if R is not being run with an interactive session. See interactive for more information.
a blimp_out object
# Run blimp script ## Not run: output <- rblimp_source("filepath/to/syntax")# Run blimp script ## Not run: output <- rblimp_source("filepath/to/syntax")
blimp_obj
Residuals scores from blimp_obj
## S4 method for signature 'blimp_obj' resid(object, ...)## S4 method for signature 'blimp_obj' resid(object, ...)
object |
A |
... |
Additional arguments passed to residuals |
A list of data frames, one per imputation, each containing the residual columns from the model.
blimp_obj
Plots an outcome's residuals against its predicted values, a predictor, the case (record) number, or the cluster, using every saved imputation.
residual_plot( model, variable, x, se = FALSE, index_thresholds = c(-3, 3), max_labels = 10, discrete_max_unique = 10L, bars = TRUE )residual_plot( model, variable, x, se = FALSE, index_thresholds = c(-3, 3), max_labels = 10, discrete_max_unique = 10L, bars = TRUE )
model |
a |
variable |
a character string naming one outcome. This is a level-1 outcome
(e.g., |
x |
what to plot the residuals against:
The special values start with |
se |
a logical value. If |
index_thresholds |
a numeric vector of reference lines for standardized residuals. Cases beyond the largest absolute value are labeled on the index plot. |
max_labels |
an integer. The maximum number of cases labeled on an index plot. |
discrete_max_unique |
an integer. A predictor with this many or fewer distinct values in a completed dataset gets category means instead of a loess curve, even if it was not declared ORDINAL, NOMINAL, or COUNT. Declared predictors and factor, character, and logical columns always do. |
bars |
|
Every quantity is computed within each imputed data set and then pooled; nothing is computed on an average of the imputations, because averaging an imputed predictor and the residual together induces a spurious association between them. The loess curve is fit within each imputation and evaluated at that imputation's own x values, from its smallest to its largest, and the curves are averaged point by point, so every imputation counts along the whole curve. The subtitle gives the number of imputations averaged; an imputation whose loess cannot be fit is left out.
With bars (the default), the index plot and plots against a predictor show one point
per case at its mean residual, with a vertical bar showing how much the residual changes
across imputations. Bars need each case to have one position on the x axis, so a plot
against a predictor whose values differ across imputations (imputed values or group-mean
centering), against predicted values, or by cluster stacks every imputation as points
instead; a message says so when bars is set explicitly. With bars = FALSE, every plot
stacks the imputations.
The residual scale is fixed by the plot, as in plot.lm:
against predicted values: raw residuals;
against a predictor, the case number, or the cluster: standardized residuals, using
the pooled residual standard deviation (the per-case model-implied standard deviation
when a variance model is fit). Reference lines are drawn at index_thresholds.
What is plotted depends on the outcome:
Continuous and ordinal outcomes (ordinal on the latent scale): residual scatter
plots with a loess curve, or category means when a predictor is discrete (see
discrete_max_unique). Category means are taken at each value within each imputation,
then averaged. A group-mean centered predictor is judged by its centered values, so it
usually gets a curve. Factor and character predictors are labeled by category name.
Nominal outcomes: binned residuals on the probability scale (Gelman & Hill, 2007), with a panel for each non-reference category. There is no index plot.
Count outcomes: Pearson residuals, using the negative binomial dispersion parameter. Each imputation uses the dispersion value from the MCMC iteration it was saved at. There is no residual-vs-predicted plot.
Level-2 residuals: one value per cluster, against level-2 predictors or as an index plot. In a clustered model, level-1 plots use within-cluster predictors only, and continuous predictors centered at their latent group mean are shown as within-cluster deviations. Group-mean centered ordinal and nominal predictors are shown on their own values, because Blimp saves their group mean on the latent scale.
With se = TRUE, each imputation's loess is evaluated with its standard error and the
curves are pooled with Rubin's rules: , and the band is
. The bands are drawn only on plots with a loess curve.
To mark cases whose outcome was imputed, add scale_imputed.
Colors come from the plot theme: points use the theme's geom color (or data_color in
blimp_style) and curves use its accent. See ggplot2::element_geom. Point transparency, reference lines, labels, and the
category-mean markers are set with blimp_style.
a ggplot2::ggplot plot
diagnostic_plots, influence_plot, probability_plot, distribution_plot,
scale_imputed, blimp_style
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000 ) # Residuals against predicted values residual_plot(m1, 'y') # Against each predictor, with 95% bands residual_plot(m1, 'y', x = c('x', 'm'), se = TRUE) # Index plot residual_plot(m1, 'y', x = '#case') + ggplot2::theme_minimal()# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( 'y ~ x m', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000 ) # Residuals against predicted values residual_plot(m1, 'y') # Against each predictor, with 95% bands residual_plot(m1, 'y', x = c('x', 'm'), se = TRUE) # Index plot residual_plot(m1, 'y', x = '#case') + ggplot2::theme_minimal()
blimp_obj
Residuals scores from blimp_obj
## S4 method for signature 'blimp_obj' residuals(object, ...)## S4 method for signature 'blimp_obj' residuals(object, ...)
object |
A |
... |
Additional arguments (unused) |
A list of data frames, one per imputation, each containing the residual columns from the model.
Add scale_imputed() to a residual_plot or influence_plot (or a
diagnostic_plots list) to draw the cases whose outcome value was imputed differently
from the observed ones, with a legend. Without it, the plots do not distinguish them. See
details for what counts as observed.
scale_imputed() takes any ggplot2 scales for color, fill,
shape, size, alpha, linewidth, linetype, or stroke, including scales from other packages,
and marks the cases by those aesthetics. With none, it marks them by color and shape:
observed values are dark grey circles (35% of the way from the theme's ink to its paper
color) and imputed values are triangles in the data_color setting of blimp_style
(blue in theme_blimp, as for the imputed values in distribution_plot), or the
second color of the theme's discrete color palette when it is not set. Curves and category
means keep the theme's accent color.
scale_imputed_manual() sets the values directly, for any of the same aesthetics.
scale_imputed(..., name = "Outcome") scale_imputed_manual( color = NULL, shape = NULL, fill = NULL, size = NULL, alpha = NULL, linewidth = NULL, linetype = NULL, stroke = NULL, ..., name = "Outcome", colour = NULL )scale_imputed(..., name = "Outcome") scale_imputed_manual( color = NULL, shape = NULL, fill = NULL, size = NULL, alpha = NULL, linewidth = NULL, linetype = NULL, stroke = NULL, ..., name = "Outcome", colour = NULL )
... |
for |
name |
the legend title, |
color, colour
|
colors for |
shape, fill, size, alpha, linewidth, linetype, stroke
|
values for |
Each point is marked by whether the plotted value is observed: a residual is observed when the case's outcome value was observed and imputed when it was missing. Random effects (level-2 residuals) are never observed, so they are marked as imputed.
The points, and the bars of residual_plot, are marked; curves, category means,
reference lines, and labels are not, and they stay out of the legend. Each layer takes the
aesthetics it supports: shape, fill, size, and stroke apply to points, and linewidth and
linetype to bars. Fill shows only on point shapes 21 to 25, so give such shapes with it;
their outline keeps the point color (data_color when color is not marked). Marking by
alpha replaces the automatic transparency of stacked points. The legend shows both groups
on every plot, also when only one is present (e.g., random effects), and draws their keys
opaque unless alpha is marked.
The marking can also be styled with scales added before or after scale_imputed(), e.g.
p + scale_imputed() + ggplot2::scale_color_viridis_d(), and adding scale_imputed()
again marks the cases by more aesthetics. Give a named scale (one with name =) to
scale_imputed() or add it before: added after, its title differs from the other marked
aesthetics' and the legend splits in two. A scale added without
scale_imputed() has no effect, because nothing is mapped to it. While the colors are
still those of the theme's default discrete palette, the dark grey and data_color above
replace them, so a scale that reproduces the default palette exactly (e.g.,
ggplot2::scale_color_hue()) gives the default colors. The legend is controlled as usual,
e.g. with ggplot2::theme(legend.position = "none").
Plots in a diagnostic_plots list with nothing to mark (probability_plot and the
binned residual plots of nominal outcomes) are left unchanged. Adding scale_imputed() to any other plot is an error.
an object to add to a plot with +.
residual_plot, influence_plot, diagnostic_plots
# Generate Data with missing outcome values mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) mydata$y[1:20] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # The theme's colors and shapes residual_plot(m1, 'y', x = '#case') + scale_imputed() # Any color or shape scale residual_plot(m1, 'y', x = '#case') + scale_imputed(ggplot2::scale_color_brewer(palette = 'Dark2')) # Chosen colors and shapes residual_plot(m1, 'y', x = 'x') + scale_imputed_manual( color = c(Observed = 'grey40', Imputed = 'red'), shape = c(Observed = 16, Imputed = 17) ) # Filled shapes and sizes residual_plot(m1, 'y', x = '#case', bars = FALSE) + scale_imputed_manual( shape = c(Observed = 21, Imputed = 24), fill = c(Observed = 'white', Imputed = 'red'), size = c(Observed = 1.5, Imputed = 2.5) ) # Every diagnostic plot diagnostic_plots(m1) + scale_imputed(ggplot2::scale_shape_manual(values = c(16, 1)))# Generate Data with missing outcome values mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) mydata$y[1:20] <- NA # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # The theme's colors and shapes residual_plot(m1, 'y', x = '#case') + scale_imputed() # Any color or shape scale residual_plot(m1, 'y', x = '#case') + scale_imputed(ggplot2::scale_color_brewer(palette = 'Dark2')) # Chosen colors and shapes residual_plot(m1, 'y', x = 'x') + scale_imputed_manual( color = c(Observed = 'grey40', Imputed = 'red'), shape = c(Observed = 16, Imputed = 17) ) # Filled shapes and sizes residual_plot(m1, 'y', x = '#case', bars = FALSE) + scale_imputed_manual( shape = c(Observed = 21, Imputed = 24), fill = c(Observed = 'white', Imputed = 'red'), size = c(Observed = 1.5, Imputed = 2.5) ) # Every diagnostic plot diagnostic_plots(m1) + scale_imputed(ggplot2::scale_shape_manual(values = c(16, 1)))
This function can set the Blimp executable location if it cannot be autodetected.
set_blimp(exec, beta = FALSE)set_blimp(exec, beta = FALSE)
exec |
a character string for the Blimp executable's location |
beta |
a logical value. If true |
By default rblimp tries to determine the location of Blimp's computational engine based on
standard operating system installation locations. This function is useful for non standard installations
or when wanting to use a beta version of blimp's computational engine (which must be installed via the updater).
TRUE if the executable is successfully set; otherwise, it produces an error.
# example code # Use blimp executable at `filepath` location ## Not run: set_blimp('filepath') # Use default blimp location but beta build set_blimp(beta = TRUE)# example code # Use blimp executable at `filepath` location ## Not run: set_blimp('filepath') # Use default blimp location but beta build set_blimp(beta = TRUE)
Show method for blimp_cp
## S4 method for signature 'blimp_cp' show(object)## S4 method for signature 'blimp_cp' show(object)
object |
A |
No return value, called for the side effect of printing the comparison table to the console.
Show method for blimp_obj
## S4 method for signature 'blimp_obj' show(object)## S4 method for signature 'blimp_obj' show(object)
object |
A |
No return value, called for the side effect of printing the model estimates to the console.
Summarizes the conditional-effect posterior draws produced by Blimp's
SIMPLE command (stored in model@simple) as a table of posterior
medians, standard deviations, and credible-interval bounds. This surfaces
simple slopes numerically – the same effects that simple_plot,
jn_plot, and jn_map visualize – which are otherwise not shown by
summary. When model@simple is non-empty, the same table is also
appended to summary(model) automatically.
Three kinds of conditional effect are reported, one block per effect:
From INTER:/SLOPE: draws, e.g.
y ~ x | m @ +1 SD. Each block has an Intercept and a Slope row.
From PARAM: draws – a generated
conditional effect whose focal is a labeled-parameter expression (e.g.
b4 + b7*mod). Each block has a single Effect row (no intercept).
simple_effects(model, ci = 0.95, digits = 3)simple_effects(model, ci = 0.95, digits = 3)
model |
a |
ci |
a value between 0 and 1 specifying the credible-interval size.
Default |
digits |
integer number of decimal places used when the result is
printed. Default |
invisibly, an object of class blimp_simple_effects: a named list
with one numeric matrix per conditional effect (rows are Intercept/Slope
or Effect; columns are the posterior summaries). Returns NULL
(invisibly) with a message when no SIMPLE output is saved.
simple_plot, jn_plot, jn_map, summary
## Not run: mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 200, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) simple_effects(m1) ## End(Not run)## Not run: mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 200, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) simple_effects(m1) ## End(Not run)
rblimp and SIMPLE commandGenerates a conditional effect plots based on the posterior summaries from the output of rblimp.
simple_plot(formula, model, ci = 0.95, xvals, ...)simple_plot(formula, model, ci = 0.95, xvals, ...)
formula |
an object of class |
model |
an |
ci |
a value between 0 and 1 specifying the credible interval size |
xvals |
a list of values to evaluate for the focal variable. If empty, they will automatically be determined |
... |
arguments passed to the internal |
To change colors use ggplot2's scale system. Both fill and color are used. See
ggplot2::aes_colour_fill_alpha for more information about setting a manual set of colors.
The transparency of the credible bands is set with blimp_style.
For nominal moderators, wrap the dummy codes in join(...) so they are
treated as a single compound moderator (one set of colored lines instead of
separate facets):
join() works for any user-controlled bundling, not just nominal dummies;
however it is only valid in the first (color/legend) position of the formula.
A bare moderator plots every value Blimp emitted for it. To plot only some of
them, use at() on its own – it filters the values and names the moderator
at the same time:
This is equivalent to writing focal | moderator + at(moderator = c(...)).
When the SIMPLE command contains more than one moderator (e.g.,
mod1 @ values and mod2 @ value), the right-hand side of the formula may list the
moderators that vary using + (e.g., focal | mod1 + mod2). Moderators that are
omitted from the formula are treated as held-constant context: their value must
be the same across the matched simple effects and is reported in the plot
subtitle.
a ggplot2::ggplot plot
jn_plot, jn_map, at, join, blimp_style
## Not run: # ---- Basic single-moderator example ---- mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) simple_plot(y ~ x | m, m1) # ---- Two moderators: first colored, second auto-faceted ---- three_way <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x*m1 + 0.3*x*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 2024 ) fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', three_way, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) simple_plot(y ~ x | m1 + m2, fit) # Pin a moderator to one SIMPLE value via `at()` simple_plot(y ~ x | m1 + at(m2 = "0"), fit) # Restrict to a subset of values simple_plot(y ~ x | m1 + at(m2 = c("-1 SD", "+1 SD")), fit) # Plot only some of a single moderator's values -- `at()` alone both # filters the values and names the moderator simple_plot(y ~ x | at(m1 = c("-1 SD", "+1 SD")), fit) # Bundle moderators (e.g. nominal dummy codes) via `join()` simple_plot(y ~ x | join(m1, m2), fit) ## End(Not run)## Not run: # ---- Basic single-moderator example ---- mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) m1 <- rblimp( 'y ~ x m x*m', mydata, center = ~ m, simple = 'x | m', seed = 10972, burn = 1000, iter = 1000 ) simple_plot(y ~ x | m, m1) # ---- Two moderators: first colored, second auto-faceted ---- three_way <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm1 ~ normal(0, 1)', 'm2 ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x*m1 + 0.3*x*m2 + 0.6*x*m1*m2, 1)' ), n = 500, seed = 2024 ) fit <- rblimp( 'y ~ x m1 m2 x*m1 x*m2 m1*m2 x*m1*m2', three_way, center = ~ x + m1 + m2, simple = 'x | m1 @ quantile and m2 @ sd', seed = 1071, burn = 1000, iter = 1000 ) simple_plot(y ~ x | m1 + m2, fit) # Pin a moderator to one SIMPLE value via `at()` simple_plot(y ~ x | m1 + at(m2 = "0"), fit) # Restrict to a subset of values simple_plot(y ~ x | m1 + at(m2 = c("-1 SD", "+1 SD")), fit) # Plot only some of a single moderator's values -- `at()` alone both # filters the values and names the moderator simple_plot(y ~ x | at(m1 = c("-1 SD", "+1 SD")), fit) # Bundle moderators (e.g. nominal dummy codes) via `join()` simple_plot(y ~ x | join(m1, m2), fit) ## End(Not run)
Creates a simulation specification that can be passed to rblimp() as the data argument.
Instead of reading existing data, rblimp() will use Blimp's SIMULATE command to generate
data and then fit the specified model to it.
SIMULATE(model, n, define = NULL, variables = NULL)SIMULATE(model, n, define = NULL, variables = NULL)
model |
Character string or vector specifying data generation equations.
Same format as |
n |
Sample size. For single-level: integer. For multilevel: named list. |
define |
Character vector or string of parameter definitions (optional). |
variables |
Formula or character string specifying which variables to save (optional). |
A blimp_simulate object (subclass of blimp_syntax) that can be passed to
rblimp() as the data argument.
rblimp_sim() for directly generating simulated data without fitting a model
# Create simulation specification sim_spec <- SIMULATE( model = c( "x = normal(0, 1)", "y = normal(10 + x*0.5, 1)" ), n = 1000 ) # View the specification print(sim_spec) # Use in rblimp to fit a model to simulated data mdl <- rblimp( model = "y ~ x", data = sim_spec, seed = 123, burn = 5000, iter = 5000 ) summary(mdl)# Create simulation specification sim_spec <- SIMULATE( model = c( "x = normal(0, 1)", "y = normal(10 + x*0.5, 1)" ), n = 1000 ) # View the specification print(sim_spec) # Use in rblimp to fit a model to simulated data mdl <- rblimp( model = "y ~ x", data = sim_spec, seed = 123, burn = 5000, iter = 5000 ) summary(mdl)
Extracts the standardized parameter estimates (and standardized correlations) from a fitted Blimp model.
standardized(object)standardized(object)
object |
A |
A base::matrix of class blimp_std containing the standardized
solutions. The matrix retains full precision for computation; see
print.blimp_std() for its rounded, aligned display.
Provides formatted summary output for blimp_obj, optionally allowing selection by variable name or block. Offers cleaner presentation than the raw estimates matrix.
## S4 method for signature 'blimp_obj' summary(object, selector, digits = 3, ...)## S4 method for signature 'blimp_obj' summary(object, selector, digits = 3, ...)
object |
A |
selector |
Optional character string specifying the variable name or block to extract. If missing, shows all estimates. Can be a variable name (e.g., "y1") or a block name (e.g., "between"). |
digits |
Integer specifying the number of decimal places for rounding. Default is 3. |
... |
Additional arguments (for S4 method compatibility). |
If selector is provided: invisibly returns a matrix or list of estimates for the selected variable/block. If no selector: returns the full estimates matrix with improved formatting.
A clean ggplot2 theme for rblimp's plots: the layout of the
figures in Applied Data Modeling in Blimp, in color. Add it to any plot, a list of plots, or
set it for the session with ggplot2::theme_set.
theme_blimp(base_size = 11, base_family = "", pointsize = 1.5, linewidth = 0.5)theme_blimp(base_size = 11, base_family = "", pointsize = 1.5, linewidth = 0.5)
base_size |
a number. The base font size in points. |
base_family |
a character string. The base font family. The default uses the system font. |
pointsize |
a number. The default point size. |
linewidth |
a number. The default line width. Smooth curves are drawn at twice it and dashed reference lines at half of it. |
Lines and axis text are black. The theme adds three colors:
Data (points in the diagnostic plots and imputed-value bars): blue "#00B0F6", set
with blimp_style(data_color = ).
Geom fill (observed-value bars): olive "#A3A500", ggplot2's ggplot2::element_geom fill.
Accent (curves and category means): coral "#F8766D", ggplot2's accent.
Zero lines are black and other reference lines dashed grey. Two groups, such as the
Johnson-Neyman significance bands, use the coral and blue; more groups, such as the
moderator levels in simple_plot, use ggplot2's default palette. Axis lines and text are
black, there is no grid, facet labels have no boxes, titles are bold and centered, and
legends sit below the plot.
Change any part by adding ggplot2::theme or blimp_style after it.
Requires ggplot2 4.0 or later, which reads default geom colors and sizes from the theme.
blimp_style, residual_plot, diagnostic_plots, distribution_plots
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # One plot residual_plot(m1, 'y') + theme_blimp() # Every plot in the session old <- ggplot2::theme_set(theme_blimp(base_size = 14)) residual_plot(m1, 'y', x = 'x') ggplot2::theme_set(old)# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp('y ~ x', mydata, nimps = 10, seed = 10972, burn = 1000, iter = 1000) # One plot residual_plot(m1, 'y') + theme_blimp() # Every plot in the session old <- ggplot2::theme_set(theme_blimp(base_size = 14)) residual_plot(m1, 'y', x = 'x') ggplot2::theme_set(old)
Generates ggplot2::ggplot plots using ggplot2::geom_line based on the output from rblimp
trace_plot(model, selector, ...)trace_plot(model, selector, ...)
model |
an |
selector |
a name of a variable, a name of a parameter, a number of a parameter, or a combination of any of them. If left empty, a plot of all parameters will be returned. See Examples. |
... |
arguments passed to internally called |
To change colors use ggplot2's scale system. Both fill and color are used. See
ggplot2::aes_colour_fill_alpha for more information about setting a manual set of colors.
a ggplot2::ggplot plot
# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( c( 'y ~ x m', 'x ~~ m' ), mydata, seed = 10972, burn = 1000, iter = 1000 ) # Generate plot of all parameters with `y` trace_plot(m1, 'y') + ggplot2::theme_minimal() # Generate plot of all parameters with `y` # Add limits to only graph first 250 iterations trace_plot(m1, 'y') + ggplot2::xlim(0, 250) + ggplot2::theme_minimal() # Generate plot of all parameters trace_plot(m1) + ggplot2::theme_minimal() # Generate plot of all parameters for `y` and `x` trace_plot(m1, c('x', 'y')) + ggplot2::theme_minimal() # Generate Plot of Parameter 5 trace_plot(m1, 5) + ggplot2::theme_minimal() # Generate plot of `x residual variance` trace_plot(m1, 'x residual variance') + ggplot2::theme_minimal() # Generate plot of Parameters 7 and 9 trace_plot(m1, c(7, 9)) + ggplot2::theme_minimal()# Generate Data mydata <- rblimp_sim( c( 'x ~ normal(0, 1)', 'm ~ normal(0, 1)', 'y ~ normal(10 + 0.5*x + m + 0.2*x*m, 1)' ), n = 100, seed = 981273 ) # Run Rblimp m1 <- rblimp( c( 'y ~ x m', 'x ~~ m' ), mydata, seed = 10972, burn = 1000, iter = 1000 ) # Generate plot of all parameters with `y` trace_plot(m1, 'y') + ggplot2::theme_minimal() # Generate plot of all parameters with `y` # Add limits to only graph first 250 iterations trace_plot(m1, 'y') + ggplot2::xlim(0, 250) + ggplot2::theme_minimal() # Generate plot of all parameters trace_plot(m1) + ggplot2::theme_minimal() # Generate plot of all parameters for `y` and `x` trace_plot(m1, c('x', 'y')) + ggplot2::theme_minimal() # Generate Plot of Parameter 5 trace_plot(m1, 5) + ggplot2::theme_minimal() # Generate plot of `x residual variance` trace_plot(m1, 'x residual variance') + ggplot2::theme_minimal() # Generate plot of Parameters 7 and 9 trace_plot(m1, c(7, 9)) + ggplot2::theme_minimal()
Deletes the managed install directory created by install_blimp. Does
not affect system installations of Blimp.
uninstall_blimp(quiet = FALSE)uninstall_blimp(quiet = FALSE)
quiet |
Logical; suppress messages and skip the interactive
confirmation prompt. Default |
TRUE if anything was removed, FALSE otherwise (invisibly).
## Not run: uninstall_blimp()## Not run: uninstall_blimp()
If Blimp was installed via install_blimp, the latest version is
re-downloaded into the managed directory. If Blimp was installed via the
system installer, the Blimp Updater application is launched (back-compat).
update_blimp()update_blimp()
If the session is not interactive, the updater is not opened.
For managed installs, the manifest is checked first and the engine is re-downloaded only if a newer version exists.
Logical indicating whether an update was started.
Calling update_blimp() on a managed install contacts
updates.blimpstats.com over HTTPS to check for a newer version of
Blimp, and downloads from it if one is available. Information may be
collected as described in the privacy policy.
See privacy policy: https://www.blimpstats.com/privacy.
# Update Blimp ## Not run: update_blimp()# Update Blimp ## Not run: update_blimp()
mitml package using by_group
Fit Model across imputations with mitml package using by_group
## S4 method for signature 'blimp_bygroup' with(data, expr, ...)## S4 method for signature 'blimp_bygroup' with(data, expr, ...)
data |
A |
expr |
An expression to evaluate on each imputation |
... |
Additional arguments (unused) |
A list of class "mitml.result" containing the results of
evaluating expr on each imputed data set.
mitml packageFit Model across imputations with mitml package
## S4 method for signature 'blimp_obj' with(data, expr, ...)## S4 method for signature 'blimp_obj' with(data, expr, ...)
data |
A |
expr |
An expression to evaluate on each imputation |
... |
Additional arguments (unused) |
A list of class "mitml.result" containing the results of
evaluating expr on each imputed data set.
A function to write out blimp input and output from a model
write.blimp(object, folder = "") ## S4 method for signature 'blimp_syntax' write.blimp(object, folder = "") ## S4 method for signature 'blimp_out' write.blimp(object, folder = "") ## S4 method for signature 'blimp_obj' write.blimp(object, folder = "")write.blimp(object, folder = "") ## S4 method for signature 'blimp_syntax' write.blimp(object, folder = "") ## S4 method for signature 'blimp_out' write.blimp(object, folder = "") ## S4 method for signature 'blimp_obj' write.blimp(object, folder = "")
object |
A |
folder |
a location to a folder to write input and output |
No return value, called for its side effect of writing 'Blimp' input and output files to disk.
write.blimp(blimp_syntax): Write blimp_syntax to file
write.blimp(blimp_out): Write blimp_out to file
write.blimp(blimp_obj): Write blimp_obj files to folder
# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit SEM Model model <- rblimp( list( structure = 'y ~ f', measurement = 'f -> x1:x5' ), mydata, seed = 3927, latent = ~ f ) # Write out input and output ## Not run: write.blimp(model, "folder_location") ## End(Not run)# Generate Data with `rblimp_sim` mydata <- rblimp_sim( c( 'f ~ normal(0, 1)', 'x1:x5 ~ normal(f, 1)', 'y ~ normal(10 + 0.3*f, 1 - .3^2)' ), n = 500, seed = 19723, variables = c('y', 'x1:x5') ) # Fit SEM Model model <- rblimp( list( structure = 'y ~ f', measurement = 'f -> x1:x5' ), mydata, seed = 3927, latent = ~ f ) # Write out input and output ## Not run: write.blimp(model, "folder_location") ## End(Not run)