Skip to contents

Apply a user-supplied model-fitting function .f to each of the M complete datasets stored in a pigauto_mi object and return the list of fits. This is the middle step of the canonical multiple-imputation workflow multi_impute() -> with_imputations() -> pool_mi().

Usage

with_imputations(
  mi,
  .f,
  ...,
  .progress = interactive(),
  .on_error = c("continue", "stop")
)

Arguments

mi

A pigauto_mi object returned by multi_impute(). Plain lists of data.frames are also accepted and treated as the datasets slot directly.

.f

A function of the form function(dataset, ...) that fits a model to one complete data.frame and returns a model object. coef() and vcov() should work on the return value (required by pool_mi()). Any model class with those two generics is supported. When mi comes from multi_impute_trees(), .f may also declare explicit tree, tree_index, or imputation arguments; these are filled with the posterior tree object, its index in mi$trees, and the imputation-dataset index. The dataset also carries matching tree, tree_index, and imputation attributes.

...

Additional arguments passed to .f for every imputation.

.progress

Logical. Show a text progress indicator (default TRUE in interactive sessions).

.on_error

One of "continue" (default) or "stop". When "continue", errors from .f are captured per imputation and the loop proceeds; a warning at the end summarises failures. When "stop", the first error aborts the entire run.

Value

A list of length M with class "pigauto_mi_fits". Each element is either a model fit or, if .f errored on that imputation and .on_error = "continue", an object of class "pigauto_mi_error" containing the captured condition. pool_mi() filters error elements automatically.

Examples

if (FALSE) { # \dontrun{
mi <- multi_impute(df, tree, m = 50)

# nlme::gls example -- zero new dependencies
fits <- with_imputations(mi, function(d) {
  d$species <- rownames(d)
  nlme::gls(
    log(Mass) ~ log(Wing.Length),
    correlation = ape::corBrownian(phy = mi$tree, form = ~species),
    data = d, method = "ML"
  )
})

pool_mi(fits)

# Tree-aware MI: with_imputations() passes the matching posterior tree
# when the callback declares a `tree` argument.
mi_t <- multi_impute_trees(df, trees, m_per_tree = 1L)
fits_t <- with_imputations(mi_t, function(d, tree) {
  d$species <- rownames(d)
  nlme::gls(
    y ~ x,
    correlation = ape::corBrownian(phy = tree, form = ~species),
    data = d, method = "ML"
  )
})
pool_mi(fits_t)
} # }