Package 'rblimp'

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

Help Index


Extract algorithmic options from Blimp output

Description

Extracts the algorithmic options section from Blimp output.

Usage

algorithm(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing algorithmic options


Convert blimp_obj to a posterior draws object

Description

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.

Usage

## 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"), ...)

Arguments

x

A blimp_obj object.

warmup

One of "exclude", "include", or "only". Default "exclude".

...

Additional arguments (unused).

Details

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.

Value

An object of class posterior::draws_array (for as_draws and as_draws_array) or posterior::draws_df (for as_draws_df).

Examples

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)

Convert blimp_obj to a 3-D MCMC array

Description

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().

Usage

## S4 method for signature 'blimp_obj'
as.array(x, warmup = c("exclude", "include", "only"), ...)

Arguments

x

A blimp_obj object.

warmup

One of "exclude", "include", or "only". Default "exclude".

...

Additional arguments (unused).

Details

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.

Value

A numeric 3-D array with dimensions ⁠[iteration, chain, parameter]⁠, named dimnames, and (when warmup = "include") an "n_warmup" attribute.

See Also

as_draws_array.blimp_obj() for the posterior::draws_array equivalent.

Examples

# 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)

Convert blimp_syntax to character vector

Description

Convert blimp_syntax to character vector

Usage

## S3 method for class 'blimp_syntax'
as.character(x, ...)

Arguments

x

A blimp_syntax object

...

Additional arguments (unused)

Value

A character string containing the formatted 'Blimp' input syntax with a header comment and all commands.


Convert blimp_obj to data.frame

Description

Convert blimp_obj to data.frame

Usage

## S4 method for signature 'blimp_obj'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)

Arguments

x

A blimp_obj object

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

Value

A data.frame containing the MCMC iterations from the model.


Convert blimp_obj to matrix

Description

Convert blimp_obj to matrix

Usage

## S4 method for signature 'blimp_obj'
as.matrix(x, ...)

Arguments

x

A blimp_obj object

...

Additional arguments (unused)

Value

A numeric matrix containing the MCMC iterations from the model.


Coerces a blimp_obj or blimp_bygroup to a mitml.list

Description

Coerces a blimp_obj or blimp_bygroup to a mitml.list

Usage

as.mitml(object)

Arguments

object

blimp_obj or blimp_bygroup object

Value

A list of class "mitml.list" containing the imputed data sets, suitable for use with functions from the 'mitml' package.


Marker for fixing a moderator at specific SIMPLE evaluated values

Description

Used inside simple_plot and jn_plot formulas to restrict the SIMPLE rows to those whose moderator was evaluated at the given label(s).

Usage

at(...)

Arguments

...

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., "Q25", "+1 SD", "0", or a parameter name) to keep.

Details

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.

Value

Calling at() outside a formula raises an error; the function only has meaning when it appears in a simple_plot() or jn_plot() formula.

See Also

simple_plot, jn_plot, jn_map, join

Examples

## 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)

S4 class for Blimp model comparison results

Description

Result object from comparing two Blimp models.

Slots

table

Matrix of comparison results

model0

The reference blimp_obj model

model

The comparison blimp_obj model

greaterThan

Logical indicating direction of comparison


S4 class for Blimp model results

Description

The main result object containing Blimp model estimates, iterations, and output.

Slots

call

The function call that created the object

estimates

Matrix of parameter estimates

burn

List of burn-in information for each chain

iterations

Data frame of MCMC iterations

psr

Data frame of Potential Scale Reduction values

imputations

List of imputed datasets

average_imp

Data frame of average imputations

variance_imp

Data frame of imputation variances

waldtest

Data frame of Wald test results

simple

Data frame for simple slopes analysis

syntax

The blimp_syntax object used to run the model

output

The blimp_out object containing raw output text


Theme settings for rblimp plots

Description

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.

Usage

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
)

Arguments

...

the color arguments spelled colour (e.g., reference_colour). All arguments must be named in full.

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 scale_imputed, and the imputed-value bars in distribution_plot. Observed values marked by scale_imputed are dark grey, mixed from the theme's ink and paper. Unset: the theme's geom color for unmarked points and the second color of the discrete colour palette for imputed values and bars.

summary_size

a positive number. Size of the category-mean markers in residual_plot and probability_plot. Unset: 3.

summary_shape

a point shape, as a number or name. Shape of the category-mean markers. Unset: a diamond (18) in residual_plot and the theme's point shape in probability_plot. Probability plots with several categories use one shape per category instead.

ribbon_alpha

a number in [0, 1]. Transparency of interval bands. Unset: 0.2 in simple_plot and the se = TRUE bands of residual_plot; 0.25 in jn_plot and jn_plot_func.

area_alpha

a number in [0, 1]. Transparency of filled areas. Unset: 0.25 for the densities in posterior_plot and 0.3 for the observed-value bars in distribution_plot.

curve_alpha

a number in [0, 1]. Transparency of the per-imputation density curves in distribution_plot. Unset: 1 / M^(1/3) for M curves (opaque for one).

reference_color

a color. Reference lines: the zero lines in the diagnostic plots, jn_plot, and jn_plot_func (unset: the theme's geom color), and the dashed thresholds, Q-Q diagonal, and influence cutoffs in the diagnostic plots (unset: "grey50").

guide_color

a color. The guide lines at 1, 2, and 3 standard deviations in the within-cluster spread plot of residual_plot. Unset: "grey70".

label_color

a color. Text labels for cases and influence cutoffs. Unset: "black".

boundary_color

a color. Johnson-Neyman boundaries: the boundary segments in jn_plot and jn_plot_func and the contour in jn_map. Unset: "black".

boundary_alpha

a number in [0, 1]. Transparency of the Johnson-Neyman boundaries. Unset: 0.5 in jn_plot and jn_plot_func; opaque in jn_map.

boundary_linewidth

a positive number. Line width of the Johnson-Neyman boundaries. Unset: the theme's line width in jn_plot and jn_plot_func; 0.6 in jn_map.

Details

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.

Value

a ggplot2::theme that sets the given settings.

See Also

theme_blimp, residual_plot, distribution_plot, jn_plot, jn_map, simple_plot, posterior_plot

Examples

# 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)

Wrapper function to run multiple instances of rblimp based on grouping variable

Description

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.

Usage

by_group(expr, group)

Arguments

expr

a call to rblimp or rblimp_fcs.

group

a character vector or index pointing to grouping variable in data set

Details

Separates by grouping to run blimp command on each individual sub data set.

Value

a list of all blimp runs by group with class of blimp_bygroup

See Also

as.mitml

Examples

# 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

Compare two Blimp models

Description

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).

Usage

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")
)

Arguments

model0

A blimp_obj. The baseline or simpler model used as the reference point.

model

A blimp_obj. The comparison model (typically more complex) to evaluate.

use

Summary statistic to use as the cutpoint from model0. Options:

  • Character: "mean" or "median"

  • Numeric < 1: Quantile proportion (e.g., 0.5 for median)

  • Numeric >= 1: Percentile (e.g., 50 for median)

  • Function: Custom function applied to model0 iterations

  • List: Multiple summary statistics

greaterThan

Logical. If TRUE (default), calculates the proportion of model iterations greater than the model0 cutpoint. If FALSE, calculates proportion less than.

suffixes

Character vector of parameter name suffixes to compare. Defaults to all R-squared values (coefficients, random effects, residual variation).

Details

The comparison works by:

  1. Computing a summary statistic (e.g., mean) from model0's posterior samples

  2. Calculating what proportion of model's posterior samples exceed this value

  3. Reporting this proportion for each parameter matching the specified suffixes

Value

A blimp_cp object containing a matrix of comparison proportions.

Note

Due to R restrictions, lists of functions will not give useful printed names.

Examples

# 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)

Convenience Function for computing conditional effects for jn_plot_func

Description

Convenience Function for computing conditional effects for jn_plot_func

Usage

compute_condeff(value1, value2)

Arguments

value1

The base value

value2

The value to change as a function of moderator

Value

a function

See Also

jn_plot_func()

Examples

# 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()
)

Cook's distance from blimp_obj

Description

Cook's distance from blimp_obj

Usage

## S4 method for signature 'blimp_obj'
cooks.distance(model, ...)

Arguments

model

A blimp_obj object

...

Additional arguments (unused)

Details

Values are computed by Blimp and averaged over every post burn-in iteration. Only single-level continuous and ordinal probit outcomes are included.

Value

A data frame with one row per case and a ⁠<dv>.cooks⁠ column for each eligible outcome.


Extract data information from Blimp output

Description

Extracts the data information section from Blimp output.

Usage

datainfo(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing data information


Describe an object

Description

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.

Usage

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,
  ...
)

Arguments

object

The object to describe.

depth

An integer (1, 2, or 3) that controls the display of vector and matrix parameters. depth=1 (default) shows only scalar parameters. depth=2 shows scalars and vectors. depth=3 shows all parameters.

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 TRUE, sorting is in decreasing order.

...

Additional arguments passed to specific methods.

hist

Logical. If TRUE (and on a Unix-like OS), a unicode histogram (histospark) is included in the output. Defaults to TRUE.

Value

An object of class describe, which is a data frame containing summary statistics and attributes for printing.

Author(s)

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.


The 'describe' class for object summaries

Description

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.

Usage

## S4 method for signature 'describe'
show(object)

Arguments

object

An object of class describe.

Slots

digits

A numeric value indicating the number of digits to display.


Produce Blimp location Conditional on Operating System

Description

This function is called when running Blimp and can be used to determine what location rblimp uses for the Blimp executable.

Usage

detect_blimp(prompt = TRUE)

Arguments

prompt

Logical; when TRUE (default) and no Blimp is found in an interactive session, ask whether to install Blimp via install_blimp. Set to FALSE to suppress the prompt and fail with an error instead (this is what has_blimp does internally).

Details

rblimp resolves Blimp's executable location in this order:

  1. Any location previously set via set_blimp.

  2. The R_BLIMP environment variable.

  3. A managed install created by install_blimp.

  4. 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).

Value

A character string of blimp's executable location.

See Also

set_blimp to set blimp location, install_blimp to install Blimp into a managed directory.

Examples

# Obtain blimp location
detect_blimp()

Every applicable diagnostic plot for a blimp_obj

Description

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.

Usage

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 & e2

Arguments

model

a blimp_obj with saved imputations.

selector

an optional character vector of outcome names. If missing, every outcome with saved residuals is included.

discrete_max_unique

an integer, passed to residual_plot and probability_plot. A predictor with this many or fewer distinct values gets category means instead of a loess curve.

bars

passed to residual_plot: TRUE (95%), a number in (0, 1], or FALSE. Plots that cannot show bars stack the imputations without a message.

x

a diagnostic_plots list.

...

for subset(), arguments passed to grepl (e.g., fixed = TRUE); otherwise unused.

i

indices or names of the plots to keep.

pattern

a regular expression matched against the plot names.

e1, e2

a diagnostic_plots list (left) and a ggplot2 component such as a theme, scale, layer, or labels (right).

Details

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").

Value

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").

See Also

residual_plot, influence_plot, probability_plot, distribution_plots

Examples

# 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")

Observed and imputed distribution of a variable in a blimp_obj

Description

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.

Usage

distribution_plot(model, variable, bins = 30, discrete_max_unique = 5L)

Arguments

model

a blimp_obj with saved imputations.

variable

a character string naming one saved variable: a variable in the model, a model-implied quantity (e.g., "y.residual", "f.latent", "y.1.probability", "y.yjt"), or a level-2 quantity (e.g., "y[school]", "x.mean[school]").

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.

Details

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.

Value

a ggplot2::ggplot plot

See Also

qq_plot, distribution_plots, residual_plot, blimp_style

Examples

# 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()

Every applicable distribution plot for a blimp_obj

Description

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.

Usage

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 & e2

Arguments

model

a blimp_obj with saved imputations.

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 TRUE, adds a ⁠<var>.qq⁠ normal Q-Q plot wherever one applies.

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 distribution_plots list.

...

for subset(), arguments passed to grepl (e.g., fixed = TRUE); otherwise unused.

i

indices or names of the plots to keep.

pattern

a regular expression matched against the plot names.

e1, e2

a distribution_plots list (left) and a ggplot2 component such as a theme, scale, layer, or labels (right).

Details

Predicted values are not included by default; request them with selector.

Value

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").

See Also

distribution_plot, qq_plot, diagnostic_plots

Examples

# 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

Extract model estimates from Blimp output

Description

Extracts the model estimates section from Blimp output.

Usage

estimates(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing model estimates


Does the system have blimp installed?

Description

Returns a logical if blimp is detected by detect_blimp

Usage

has_blimp()

Details

This function uses detect_blimp to determine if blimp is installed.

Value

a logical

See Also

detect_blimp

Examples

# Detect if system has blimp
has_blimp()

Leverage and Cook's distance plots for an outcome in a blimp_obj

Description

Index plots of the leverage and Cook's distance values Blimp computes for an outcome. Requires a version of Blimp that supports influence output.

Usage

influence_plot(
  model,
  variable,
  measure = c("leverage", "cooks"),
  max_labels = 10
)

Arguments

model

a blimp_obj.

variable

a character string naming one outcome.

measure

which values to plot: "leverage", "cooks", or both (the default), which are drawn as two panels.

max_labels

an integer. The maximum number of cases labeled in each panel.

Details

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 2p/n2p/n and 3p/n3p/n for leverage, where pp is the number of columns in the design (the sum of the leverages), and at 4/n4/n for Cook's distance. Cases above 3p/n3p/n or 4/n4/n 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.

Value

a ggplot2::ggplot plot

See Also

residual_plot, diagnostic_plots, influence, scale_imputed, blimp_style

Examples

# 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)

Influence values from blimp_obj

Description

Influence values from blimp_obj

Usage

## S4 method for signature 'blimp_obj'
influence(model, ...)

Arguments

model

A blimp_obj object

...

Additional arguments (unused)

Details

Values are computed by Blimp and averaged over every post burn-in iteration. Only single-level continuous and ordinal probit outcomes are included.

Value

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).


Install the Blimp computational engine

Description

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.

Usage

install_blimp(dir = NULL, force = FALSE, quiet = FALSE, linux_variant = NULL)

Arguments

dir

Install directory. Defaults to a hidden, user-writable per-OS location (⁠~/.blimp/⁠ on macOS and Linux, ⁠%LOCALAPPDATA%/Blimp/⁠ on Windows), overridable via the R_BLIMP_HOME environment variable.

force

Logical; overwrite an existing managed install, or proceed even when a system installation of Blimp is detected. Default FALSE. When both managed and system installations exist, the managed install takes precedence in detect_blimp.

quiet

Logical; suppress progress messages. Default FALSE.

linux_variant

Optional character; "ubuntu" or "rhel8". When NULL (default), the variant is auto-detected from ⁠/etc/os-release⁠. Ignored on macOS and Windows.

Details

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.

Value

Path to the installed blimp executable, invisibly.

Privacy

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.

See Also

uninstall_blimp, update_blimp

Examples

## 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)

Two-dimensional Johnson-Neyman map of a conditional slope

Description

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)⁠:

∂y∂x=a+b m1+c m2+d m1m2.\frac{\partial y}{\partial x} = a + b\,m_1 + c\,m_2 + d\,m_1 m_2.

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.

Usage

jn_map(formula, model, ci = 0.95, n_grid = 100, ...)

Arguments

formula

an object of class formula of the form outcome ~ focal | m1 + m2. Exactly two bare moderators are required; additional moderators present in the SIMPLE statement must be pinned via at().

model

an blimp_obj. The model must have a SIMPLE command output saved.

ci

a value between 0 and 1 specifying the credible-interval size for the significance contour. Default 0.95.

n_grid

integer length-1 or length-2. Number of grid points along m1 and m2. Default 100 (i.e. 100 x 100 cells).

...

currently unused.

Value

a ggplot2::ggplot plot. Attribute "grid" carries the per-cell data frame (with lower, median, upper, sig columns).

See Also

jn_plot, simple_plot, at, join, blimp_style

Examples

## 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)

Function to generate a Johnson-Neyman Plot of Conditional Slope with rblimp

Description

Generates a Johnson-Neyman Plot based on the posterior summaries from the output of rblimp.

Usage

jn_plot(formula, model, ci = 0.95, ...)

Arguments

formula

an object of class formula to specify simple effect to plot. The formula usually has the form outcome ~ focal | moderator. See Details below for nominal moderators and for compound-parameter (PARAM) effects.

model

an blimp_obj.

ci

a value between 0 and 1 specifying the credible interval size

...

passed bounds search algorithm. See jn_plot_func for details.

Details

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).

Compound-parameter (PARAM) effects

A 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.

Value

a ggplot2::ggplot plot. The bounding values are saved in the attribute 'bounds'.

See Also

jn_plot_func, jn_map, simple_plot, simple_effects, at, join, blimp_style

Examples

## 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)

Function to generate a Johnson-Neyman Plot of Conditional Slope based on a function to produce the conditional effect.

Description

Generates a Johnson-Neyman Plot using a function to produce the conditional effect

Usage

jn_plot_func(func, xrange, ci = 0.95, ...)

Arguments

func

a function used to compute the conditional effect on moderator.

xrange

a numeric of length two with the min and max of the x-axis

ci

a value between 0 and 1 specifying the credible interval size

...

values passed to internal boundary search algorithm. See Details below.

Details

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:

n_initial

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.

refine_tol

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.

max_iter

Maximum number of iterations for binary search refinement per boundary. Prevents infinite loops if tolerance cannot be achieved. Default is 100.

adaptive

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.

Value

a ggplot2::ggplot plot. The bounding values are saved in the attribute 'boundaries'.

See Also

compute_condeff(), blimp_style

Examples

# 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()
)

Marker for bundling multiple SIMPLE moderators into one compound moderator

Description

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.

Usage

join(...)

Arguments

...

bare moderator names (at least two) to bundle together.

Details

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.

Value

Calling join() outside a formula raises an error; it only has meaning inside simple_plot() / jn_plot() formulas.

See Also

simple_plot, jn_plot, jn_map, at

Examples

## 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)

Create APA-formatted table of model results

Description

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.

Usage

model_table(
  object,
  selector,
  digits = 3,
  caption = NULL,
  show_chains = TRUE,
  show_neff = FALSE
)

Arguments

object

A blimp_obj containing model results.

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.

Details

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.

Value

Invisibly returns the HTML content. Primary purpose is displaying in Viewer.

Examples

# 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")

Extract model fit from Blimp output

Description

Extracts the model fit section from Blimp output.

Usage

modelfit(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing model fit information


Extract model information from Blimp output

Description

Extracts the model information section from Blimp output.

Usage

modelinfo(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing model information


Return variable names from blimp_obj object

Description

Return variable names from blimp_obj object

Usage

## S4 method for signature 'blimp_obj'
names(x)

Arguments

x

A blimp_obj object

Value

A character vector of variable names from the average imputation data.


Extract output from blimp_obj

Description

Extracts the raw Blimp output text from a blimp_obj.

Usage

output(object)

Arguments

object

A blimp_obj object

Value

A blimp_out object containing the raw Blimp output text


Function to generate graph posterior density plots for parameters

Description

Generates ggplot2::ggplot plots using ggplot2::geom_density based on the output from rblimp

Usage

posterior_plot(model, selector, ...)

Arguments

model

an blimp_obj.

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 ggplot2::facet_wrap when used.

Details

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.

Value

a ggplot2::ggplot plot

Examples

# 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()

Predicted scores from blimp_obj

Description

Predicted scores from blimp_obj

Usage

## S4 method for signature 'blimp_obj'
predict(object, ...)

Arguments

object

A blimp_obj object

...

Additional arguments (unused)

Value

A list of data frames, one per imputation, each containing the predicted values and probability columns from the model.


Print method for blimp_simple_effects

Description

Print method for blimp_simple_effects

Usage

## S3 method for class 'blimp_simple_effects'
print(x, digits = attr(x, "digits"), ...)

Arguments

x

A blimp_simple_effects object from simple_effects.

digits

Integer number of decimal places. Defaults to the value stored on x (or 3).

...

Unused.

Value

x, invisibly.


Print standardized solutions

Description

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.

Usage

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

Arguments

x

A blimp_std object, as returned by standardized().

digits

Integer specifying the number of decimal places to display. Default is 3.

...

Additional arguments passed to print().

Value

The blimp_std object x (invisibly). Called for its side effect of printing the rounded, aligned table to the console.


Print blimp_syntax

Description

Print blimp_syntax

Usage

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

Arguments

x

A blimp_syntax object

...

Additional arguments (unused)

Value

The blimp_syntax object (invisibly). Called for its side effect of printing the formatted syntax to the console.


Predicted probabilities across a predictor for an outcome in a blimp_obj

Description

Plots the predicted probability of each category of an ordinal or nominal outcome against a predictor, using every saved imputation.

Usage

probability_plot(model, variable, x, discrete_max_unique = 10L)

Arguments

model

a blimp_obj with saved imputations.

variable

a character string naming an ordinal or nominal outcome.

x

a character string naming one predictor of variable.

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.

Details

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.

Value

a ggplot2::ggplot plot

See Also

residual_plot, diagnostic_plots, blimp_style

Examples

# 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')

Extract Potential Scale Reduction (PSR) output

Description

Extracts the PSR convergence diagnostic section from Blimp output.

Usage

psr(object)

Arguments

object

A blimp_obj or blimp_out object

Value

A blimp_out object containing PSR output


Normal Q-Q plot of a variable in a blimp_obj

Description

Plots the standardized values of one variable against standard normal quantiles, one set of points per completed dataset, overlaid.

Usage

qq_plot(model, variable, discrete_max_unique = 5L)

Arguments

model

a blimp_obj with saved imputations.

variable

a character string naming one saved variable: a variable in the model, a model-implied quantity (e.g., "y.residual", "f.latent", "y.1.probability", "y.yjt"), or a level-2 quantity (e.g., "y[school]", "x.mean[school]").

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.

Details

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.

Value

a ggplot2::ggplot plot

See Also

distribution_plot, distribution_plots, blimp_style

Examples

# 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')

Wrapper functions to provide Blimp functions in R

Description

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.

Usage

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
)

Arguments

model

a character string or vector/list of character strings. Specifies Blimp's MODEL command. See details.

data

a data.frame or a SIMULATE object. If a data.frame, the data set used by Blimp. If a SIMULATE object (created with SIMULATE()), Blimp will generate simulated data instead of using existing data

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 rblimp will use the given file path as a temporary directory instead of creating one with tempdir

add_save

a single logical value or a list of logical values. If TRUE then saveLatent, saveResidual, and savePredicted will be included in OPTIONS command. Otherwise, it will be coerced to a list. The elements of the list should labeled latent, residual, and predicted each containing a single logical value that can be used to toggle on or off them individually. Missing elements will be defaulted to TRUE.

print_output

The type of output printed to the console. 'iteration' or logical TRUE is only iteration history, 'none' or logical FALSE suppresses all output to console, and 'all' prints all output to 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

Details

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.

Value

blimp_obj

See Also

Examples

# 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)

Getting Started with rblimp

Description

A guide to installing and configuring Blimp software for use with rblimp.

Installing Blimp Software

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.

Automatic Update Checks

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.

Function Reference

Model Fitting:

Simulation:

Output & Analysis:

Visualization (see rblimp_plots for styling and saving plots):

Utilities:

Setup & Configuration:

Additional Resources


Styling and Saving rblimp Plots

Description

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.

Themes

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

rblimp's own settings

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)

Styling many plots at once

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")

Saving

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)
}

Examples

# 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)

Simulate data using Blimp

Description

Generate simulated datasets using Blimp's SIMULATE command. Supports both single-level and multilevel data generation.

Usage

rblimp_sim(
  model,
  n,
  seed,
  define = NULL,
  variables = NULL,
  tmpfolder,
  nopowershell = FALSE
)

Arguments

model

Character string or vector specifying data generation equations. Can be specified as a vector: c("x = normal(0, 1)", "y = normal(10, 1)") OR as a single string with newlines/semicolons: "x = normal(0, 1); y = normal(10, 1);" For multilevel: use named list with arbitrary level names (e.g., list(schools = ..., students = ...)). The sample size determines the level hierarchy (largest = level-1, smallest = highest level).

n

Sample size. For single-level: integer (e.g., 1000). For multilevel: named list with sample sizes (e.g., list(students = 1000, schools = 100)). Names must match the names used in model list. Sample sizes must be unique.

seed

Random seed for reproducibility.

define

Character vector or string of parameter definitions (optional). Can be c("b0 = 10", "b1 = 0.5") OR "b0 = 10; b1 = 0.5;".

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 tempdir.

nopowershell

Windows only. Uses cmd.exe instead of powershell.

Value

A data.frame with simulated data. The returned object has two attributes:

syntax

The Blimp syntax used for simulation (blimp_syntax object)

output

The raw Blimp output (blimp_out object)

Access these with attr(result, "syntax") and attr(result, "output").

See Also

SIMULATE() for creating a simulation specification to use with rblimp()

Examples

# 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)

Runs an 'imp' file with Blimp

Description

This function runs 'imp' file with Blimp and captures the output only.

Usage

rblimp_source(file, plots = FALSE, output = TRUE, nopowershell = FALSE)

Arguments

file

a character string to the 'imp' file's location

plots

a logical. Setting to TRUE will generate the data required for plotting by Blimp

output

The type of output printed to the console. 'iteration' or logical TRUE is only iteration history, 'none' or logical FALSE suppresses all output to console, and 'all' prints all output to console.

nopowershell

Windows only. Uses cmd.exe with some limited functions (instead of powershell).

Details

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.

Value

a blimp_out object

Examples

# Run blimp script
## Not run: output <- rblimp_source("filepath/to/syntax")

Residuals scores from blimp_obj

Description

Residuals scores from blimp_obj

Usage

## S4 method for signature 'blimp_obj'
resid(object, ...)

Arguments

object

A blimp_obj object

...

Additional arguments passed to residuals

Value

A list of data frames, one per imputation, each containing the residual columns from the model.


Residual diagnostic plots for an outcome in a blimp_obj

Description

Plots an outcome's residuals against its predicted values, a predictor, the case (record) number, or the cluster, using every saved imputation.

Usage

residual_plot(
  model,
  variable,
  x,
  se = FALSE,
  index_thresholds = c(-3, 3),
  max_labels = 10,
  discrete_max_unique = 10L,
  bars = TRUE
)

Arguments

model

a blimp_obj with saved imputations.

variable

a character string naming one outcome. This is a level-1 outcome (e.g., "y"), a level-2 random-intercept residual (e.g., "y[school]"), or a level-2 latent random effect declared on the cluster identifier's LATENT line. For a nominal outcome, the parent name (e.g., "y") plots every non-reference category and a category name (e.g., "y.2") plots one.

x

what to plot the residuals against:

  • "#predicted": the predicted values (the default when the outcome has them).

  • one or more predictor names: a separate panel for each predictor.

  • "#case": the record number (an index plot; the default otherwise).

  • "#cluster": clusters ordered by their residual spread (clustered continuous outcomes).

The special values start with ⁠#⁠ so they cannot clash with a variable name.

se

a logical value. If TRUE, adds 95% pointwise bands around the loess curve. See details.

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

TRUE, FALSE, or a number in (0, 1]. With bars, each case is one point at its mean residual across imputations, with a vertical bar covering the middle share of its imputations: 95% for TRUE, that share for a number (0.8 is the middle 80%), and the full range for 1. FALSE stacks every imputation as points. See details.

Details

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: T=W+B+B/MT = W + B + B/M, and the band is ±1.96T\pm 1.96\sqrt{T}. 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.

Value

a ggplot2::ggplot plot

See Also

diagnostic_plots, influence_plot, probability_plot, distribution_plot, scale_imputed, blimp_style

Examples

# 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()

Residuals scores from blimp_obj

Description

Residuals scores from blimp_obj

Usage

## S4 method for signature 'blimp_obj'
residuals(object, ...)

Arguments

object

A blimp_obj object

...

Additional arguments (unused)

Value

A list of data frames, one per imputation, each containing the residual columns from the model.


Mark cases whose outcome was imputed

Description

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.

Usage

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
)

Arguments

...

for scale_imputed(), ggplot2 scales, e.g. ggplot2::scale_color_brewer(palette = "Dark2") or ggplot2::scale_shape_manual(values = c(21, 24)). For scale_imputed_manual(), other arguments passed to ggplot2::scale_discrete_manual (e.g., labels).

name

the legend title, "Outcome" by default, or NULL for no title. A title from a named scale (passed in or already on the plot) or from ggplot2::labs is used instead.

color, colour

colors for Observed and Imputed cases, e.g. c(Observed = "black", Imputed = "red"). Give one of the two spellings.

shape, fill, size, alpha, linewidth, linetype, stroke

values for Observed and Imputed cases, e.g. shape = c(Observed = 21, Imputed = 24) with fill = c(Observed = "white", Imputed = "red").

Details

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.

Value

an object to add to a plot with +.

See Also

residual_plot, influence_plot, diagnostic_plots

Examples

# 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)))

Set Blimp Executable Location

Description

This function can set the Blimp executable location if it cannot be autodetected.

Usage

set_blimp(exec, beta = FALSE)

Arguments

exec

a character string for the Blimp executable's location

beta

a logical value. If true rblimp will use the beta version which must be installed

Details

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).

Value

TRUE if the executable is successfully set; otherwise, it produces an error.

Examples

# 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

Description

Show method for blimp_cp

Usage

## S4 method for signature 'blimp_cp'
show(object)

Arguments

object

A blimp_cp object

Value

No return value, called for the side effect of printing the comparison table to the console.


Show method for blimp_obj

Description

Show method for blimp_obj

Usage

## S4 method for signature 'blimp_obj'
show(object)

Arguments

object

A blimp_obj object

Value

No return value, called for the side effect of printing the model estimates to the console.


Posterior summaries of conditional (simple) effects

Description

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:

Conditional intercept and slope

From ⁠INTER:⁠/⁠SLOPE:⁠ draws, e.g. ⁠y ~ x | m @ +1 SD⁠. Each block has an Intercept and a Slope row.

Compound-parameter effect

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).

Usage

simple_effects(model, ci = 0.95, digits = 3)

Arguments

model

a blimp_obj. The model must have a SIMPLE command output saved.

ci

a value between 0 and 1 specifying the credible-interval size. Default 0.95.

digits

integer number of decimal places used when the result is printed. Default 3.

Value

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.

See Also

simple_plot, jn_plot, jn_map, summary

Examples

## 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)

Function to generate conditional regression equation plots (i.e., simple effects) with rblimp and SIMPLE command

Description

Generates a conditional effect plots based on the posterior summaries from the output of rblimp.

Usage

simple_plot(formula, model, ci = 0.95, xvals, ...)

Arguments

formula

an object of class formula to specify simple effect to plot. The formula must have the following form: outcome ~ focal | moderator. See Details below for nominal moderators and for SIMPLE statements that include more than one moderator.

model

an blimp_obj. The model must have a SIMPLE command output saved.

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 ggplot2::geom_line call used to generate the median lines.

Details

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):

focal | join(moderator.1, moderator.2)\code{focal | join(moderator.1, moderator.2)}

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:

focal | at(moderator = c("-1 SD", "+1 SD"))\code{focal | at(moderator = c("-1 SD", "+1 SD"))}

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.

Value

a ggplot2::ggplot plot

See Also

jn_plot, jn_map, at, join, blimp_style

Examples

## 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)

Create a SIMULATE specification for use in rblimp()

Description

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.

Usage

SIMULATE(model, n, define = NULL, variables = NULL)

Arguments

model

Character string or vector specifying data generation equations. Same format as rblimp_sim().

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).

Value

A blimp_simulate object (subclass of blimp_syntax) that can be passed to rblimp() as the data argument.

See Also

rblimp_sim() for directly generating simulated data without fitting a model

Examples

# 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)

Extract standardized solutions from Blimp

Description

Extracts the standardized parameter estimates (and standardized correlations) from a fitted Blimp model.

Usage

standardized(object)

Arguments

object

A blimp_obj object

Value

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.

See Also

print.blimp_std()


Summary method for blimp_obj

Description

Provides formatted summary output for blimp_obj, optionally allowing selection by variable name or block. Offers cleaner presentation than the raw estimates matrix.

Usage

## S4 method for signature 'blimp_obj'
summary(object, selector, digits = 3, ...)

Arguments

object

A blimp_obj object containing model results.

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).

Value

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 theme for rblimp plots

Description

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.

Usage

theme_blimp(base_size = 11, base_family = "", pointsize = 1.5, linewidth = 0.5)

Arguments

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.

Details

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.

Value

a ggplot2::theme

See Also

blimp_style, residual_plot, diagnostic_plots, distribution_plots

Examples

# 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)

Function to generate trace plots of the burn-in iterations

Description

Generates ggplot2::ggplot plots using ggplot2::geom_line based on the output from rblimp

Usage

trace_plot(model, selector, ...)

Arguments

model

an blimp_obj.

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 ggplot2::facet_wrap when used.

Details

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.

Value

a ggplot2::ggplot plot

Examples

# 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()

Remove the managed Blimp installation

Description

Deletes the managed install directory created by install_blimp. Does not affect system installations of Blimp.

Usage

uninstall_blimp(quiet = FALSE)

Arguments

quiet

Logical; suppress messages and skip the interactive confirmation prompt. Default FALSE.

Value

TRUE if anything was removed, FALSE otherwise (invisibly).

See Also

install_blimp

Examples

## Not run: uninstall_blimp()

Update the installed Blimp engine

Description

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).

Usage

update_blimp()

Details

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.

Value

Logical indicating whether an update was started.

Privacy

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.

See Also

install_blimp

Examples

# Update Blimp
## Not run: update_blimp()

Fit Model across imputations with mitml package using by_group

Description

Fit Model across imputations with mitml package using by_group

Usage

## S4 method for signature 'blimp_bygroup'
with(data, expr, ...)

Arguments

data

A blimp_bygroup object

expr

An expression to evaluate on each imputation

...

Additional arguments (unused)

Value

A list of class "mitml.result" containing the results of evaluating expr on each imputed data set.


Fit Model across imputations with mitml package

Description

Fit Model across imputations with mitml package

Usage

## S4 method for signature 'blimp_obj'
with(data, expr, ...)

Arguments

data

A blimp_obj object

expr

An expression to evaluate on each imputation

...

Additional arguments (unused)

Value

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

Description

A function to write out blimp input and output from a model

Usage

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 = "")

Arguments

object

A blimp_obj.

folder

a location to a folder to write input and output

Value

No return value, called for its side effect of writing 'Blimp' input and output files to disk.

Methods (by class)

  • 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

Examples

# 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)