Package {Conigrave}


Type: Package
Title: Flexible Tools for Multiple Imputation
Version: 0.5.0
Encoding: UTF-8
Description: Searches for parsimonious regression models, builds correlation tables, and plots fitted interactions for data frames and multiply imputed data. Supports linear and generalized linear model search, custom fitting and scoring functions, and response-scale predictions from selected models.
License: GPL-3
Imports: ggplot2 (≥ 3.1.1), tibble, mitools(≥ 2.4)
Suggests: ppcor(≥ 1.1), miceadds(≥ 3.2-48)
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-25 02:26:14 UTC; marine
Author: James Conigrave [aut, cre]
Maintainer: James Conigrave <james.conigrave@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-25 03:40:09 UTC

Search for a parsimonious regression model

Description

Search predictor sets and hierarchical interactions, retaining candidates that improve the fit score after subtracting a complexity penalty. Supports linear regression, generalized linear models, and custom fitters.

Usage

autoModel(
  data,
  outcome,
  genepool = NULL,
  extinction = 30,
  children = 20,
  penalty = 0.03,
  samples = 5,
  include = c(),
  exclude = c(),
  set.seed = NULL,
  family = NULL,
  fit = NULL,
  score = NULL,
  max_evaluations = 1000L,
  max_order = 3L,
  validation = NULL,
  validation_score = NULL
)

Arguments

data

A data frame, a mitools::imputationList(), or an Amelia object. Completed data sets must have the same rows in the same order, with matching row names, column types, and factor levels.

outcome

Name of the response column.

genepool

Character vector of eligible predictors. By default, use all columns except the outcome and any excluded predictors.

extinction

Stop after this many generations without improvement.

children

Number of candidate proposals per generation.

penalty

Non-negative cost per non-intercept coefficient. A term that adds more than one coefficient incurs the cost for each one.

samples

Number of bootstrap resamples for stability. Use zero to skip.

include

Required predictors or comma-separated interactions. For example, include = "x,z" requires x, z, and x:z. Required names must be eligible and cannot also be excluded.

exclude

Character vector of predictor names to omit from the search.

set.seed

Optional search seed. If supplied, the caller's random-number state is restored on exit.

family

A GLM family object, such as stats::binomial() or stats::poisson(). Use NULL for ordinary linear regression, or leave it unset when supplying a custom fitter.

fit

Optional deterministic function function(formula, data). Supply it with score, not family. Its fitted object needs coef() (returning a numeric vector) and summary() methods, and a vcov() method for pooling across imputations.

score

For a custom fit, a function of the fitted model that returns one finite number to maximize, for example negative AIC.

max_evaluations

Maximum number of distinct training candidates attempted, including failed fits. Fitting the winner again and running optional stability calculations are additional.

max_order

Maximum interaction order, including for required terms. Use one to search only main effects.

validation

Optional independent data with the outcome and all eligible predictors. Supply a single frame, reused for each fit, or one completed data set per fit. These data do not influence model selection.

validation_score

Optional function function(fitted_model, newdata) returning one numeric held-out score. Required when validating a custom fitter. newdata is transformed using the training means and scales.

Details

Search and scoring. Every candidate uses the same complete rows across the outcome, eligible predictors, and all imputations. Numeric predictors are standardized within each completed data set. Factors are kept as factors even if their labels look numeric. Only the built-in linear model standardizes the response.

The search averages adjusted R-squared (linear models), the fraction of null deviance explained (GLMs), or the supplied custom score across imputations. Fitness is this score minus the penalty times the number of non-intercept coefficients. If nothing is required, the search starts with an intercept-only candidate. That candidate counts toward the budget and can win. The search is heuristic; it does not guarantee an exhaustive search or the best possible model.

Validation and stability. The default held-out score is one minus the ratio of prediction loss to the loss from predicting the training response mean. Loss is squared error for linear models and family deviance for GLMs. The result can be negative. With multiple imputations, this is a mean of per-fit scores, not a score for the mean prediction. Training scores are not estimates of predictive accuracy.

Stability is one minus the bootstrap standard deviation of the training score divided by the absolute full-data score. Each replicate samples row indices with replacement and uses the same indices for every imputation. A zero full-data score or an undefined calculation gives NA. Stability is not held-out performance.

Value

An object of class autoModel, stored as a list. Its main components are listed below. Print the object for a compact report, or use summary() for coefficient estimates and bootstrap stability.

formula, coefficients

The selected formula and coefficient estimates (pooled across imputations). Use formula() and coef() to extract them.

history

One row per strict improvement in chronological order; the last row is the winner. Columns are generation (zero for initial candidates), formula (text), n_coefficients (excluding the intercept), score (unpenalized), fitness (penalized), and stability.

diagnostics

Counts of distinct training candidates attempted, succeeded, and failed, the number of search generations after initialization, and stop_reason: "complete" (all zero- or one-predictor candidates considered), "budget" (evaluation limit), or "stagnation" (no improvement for extinction generations). Counts exclude bootstrap, validation, and the final fit.

result_history

A tibble of improving candidates, best first. call is the model formula, length counts non-intercept coefficients, and fitness includes the penalty. The unpenalized score is R2 (adjusted R-squared) for built-in linear models and score otherwise. stability is the optional bootstrap summary.

result

The winning fit summary, or the pooled coefficient summary for multiple imputations. Coefficients refer to the modeling scales, which include standardized numeric predictors.

fits, transforms

One fitted model and table of training centers and scales per completed data set. Use predict.autoModel with raw data rather than applying these transformations yourself.

plot

A plot of improving candidates' penalized training scores by search generation.

evaluations, metric, validation_score

The number of attempted training candidates, the training metric name, and the mean held-out score (NULL if no validation was requested).

See Also

autoModel-methods, predict.autoModel, int.plot

Examples

## Not run: 
# Run manually: the search repeatedly fits regression models.
autoModel(mtcars, "mpg", set.seed = 10, children = 3)

m <- autoModel(
  mtcars, "am", genepool = c("wt", "hp"),
  include = "wt,hp", family = binomial(),
  max_evaluations = 8, samples = 0, set.seed = 11
)
predict(m, newdata = data.frame(wt = 3.5, hp = 150))
int.plot(m, predictor = "wt", moderator = "hp")$plot

## End(Not run)

Inspect a selected model

Description

Print the winning formula, scores, and search diagnostics without dumping the fitted models. Use the accessors to work with unrounded results.

Usage

## S3 method for class 'autoModel'
formula(x, ...)

## S3 method for class 'autoModel'
coef(object, ...)

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

## S3 method for class 'autoModel'
summary(object, ...)

## S3 method for class 'summary.autoModel'
print(x, ..., digits = 3L)

## S3 method for class 'autoModel'
plot(x, ...)

Arguments

x, object

An object returned by autoModel; for the summary print method, the result of summary() on that object.

...

Additional arguments passed to the ggplot print method by plot(); otherwise unused.

digits

Number of significant digits in printed scores and estimates.

Details

Numeric predictors are standardized within each training data set. The built-in linear model also standardizes the response; GLM coefficients are on the link scale. With multiple imputations, estimates and standard errors are pooled on the modeling scale. Standard errors do not account for model selection. Bootstrap stability describes variation in the training score, not predictive accuracy.

Value

formula() returns the selected R formula and coef() its numeric coefficient vector. summary() returns a list with the formula, training metric, winning row of history (winner), held-out score, search diagnostics, imputation count, and a coefficient matrix. Standard errors are included for built-in and pooled fits, and for custom fits with a compatible covariance matrix. Printing returns its input invisibly. plot() draws and invisibly returns the ggplot of improving candidates; use x$plot to customize it first.


Check that requested column names exist

Description

Check a data frame, each completed data set, or a supplied vector of available names. Suggest similar names by Levenshtein edit distance when a requested name is missing.

Usage

check_names(x, data)

Arguments

x

Character vector of requested names.

data

A data frame, imputation list, Amelia object, or character vector of available names.

Value

Invisibly returns NULL if all names exist. Otherwise, raises an error listing the missing names.

See Also

find_similar

Examples

check_names(c("mpg", "wt"), mtcars)

Build correlation tables

Description

Calculate Pearson, Spearman, or Kendall correlations for numeric columns. Return a formatted table or use output = "long" for unrounded statistics suitable for further analysis. correlatrix() is an alias for ctrx().

Usage

ctrx(
  data,
  x = NULL,
  y = NULL,
  triangle = "both",
  round = 2,
  method = "pearson",
  n.matrix = FALSE,
  abbreviate = 100,
  stars = c(0.05, 0.01, 0.001),
  partial = c(),
  describe = FALSE,
  leading.zero = TRUE,
  ...,
  output = c("table", "long")
)

Arguments

data

A data frame or completed data sets in an imputation list or Amelia object. Selected columns must be numeric vectors.

x

Column names for the table's horizontal axis. Defaults to all columns.

y

Column names for the vertical axis. Defaults to x.

triangle

"both", "lower", or "upper". The triangular layouts require identical x and y.

round

Number of decimal places in formatted output.

method

One of "pearson", "spearman", or "kendall".

n.matrix

If TRUE, show complete-pair counts instead of correlations in the formatted table. A count is NA if it differs across imputations.

abbreviate

Minimum label length passed to base::abbreviate().

stars

P-value thresholds. Each threshold strictly greater than the p-value adds one star. Use NULL to omit stars.

partial

Numeric control variables, identified by column name. They are removed from the table axes, and observations must be complete on both variables and all controls. Partial correlations are not supported across multiple imputations.

describe

FALSE, TRUE for mean and standard deviation (with missing values removed), or a named list of functions that each return one numeric value. Adds columns for the row variables. For imputed data, each descriptive statistic is averaged across imputations.

leading.zero

If FALSE, omit leading zeros in formatted correlations.

...

var.names is accepted for compatibility but is deprecated. Use x instead.

output

"table" for formatted output, or "long" for one unrounded result per distinct off-diagonal pair. With "long", the axis and triangle selections still apply, but formatting and descriptive columns are not used. Counts are included regardless of n.matrix.

Details

For ordinary Pearson correlations, pairs with fewer than three complete observations have missing estimates. Constant variables or too few complete observations for the chosen test give missing statistics for that pair without dropping other pairs. With multiple imputations, estimates require the optional miceadds package and are pooled using miceadds::micombine.cor(). Partial estimates require ppcor. Count-only tables need neither package.

Value

A data frame. Formatted output places y on the rows and x on the columns, or uses a triangular layout. Long output has columns x, y, estimate, p.value, and n. Pairs are not repeated in reverse order.

See Also

get.numeric

Examples

vars <- c("mpg", "wt", "hp")
ctrx(mtcars, x = vars, triangle = "lower", describe = TRUE)
ctrx(mtcars, x = "mpg", y = c("wt", "hp"), method = "spearman", n.matrix = TRUE)
ctrx(mtcars, x = vars, output = "long")

Match strings by minimum similarity

Description

Find strings in y that are at least percent similar to any string in x.

Usage

find_similar(x, y, percent = 50)

Arguments

x

Character vector of query strings.

y

Character vector of possible matches.

percent

Minimum similarity, from 0 to 100. Use 100 for exact matches. The default is 50.

Details

Similarity is 100 times one minus the Levenshtein edit distance divided by the longer string length. Swapping two adjacent letters counts as two edits. Two empty strings match exactly. Missing strings are ignored.

Value

A sorted character vector of unique matches, or character(0) if none match.

Examples

find_similar("colour", c("color", "colour", "shape"), percent = 80)

Keep numeric columns

Description

Remove non-numeric columns from a data frame or from each completed data set. A single numeric column is kept as a data frame, not a vector.

Usage

get.numeric(x)

Arguments

x

A data frame, imputation list, or Amelia object.

Value

A data frame for ordinary input, or an imputation list for imputed input. For imputed input, the retained column names and their order must agree across completed data sets.

See Also

ctrx

Examples

get.numeric(iris)

Plot a two-way or three-way interaction

Description

Fit a standardized linear interaction from data, or plot predictions from an existing model without refitting it.

Usage

int.plot(
  data,
  outcome,
  predictor,
  moderator,
  y.lim = c(-1, 1),
  x.lim = c(-1, 1),
  x.lab = "auto",
  y.lab = "auto",
  title = "auto",
  title.size = 15,
  SDs = 1,
  legend.name = "auto",
  colour = "ghostwhite",
  show.points = FALSE,
  newdata = NULL
)

Arguments

data

A data frame, completed data sets in an imputation list or Amelia object, or a fitted autoModel, lm, or glm.

outcome

Name of the response column. Required when supplying data. Inferred from the fitted model if omitted.

predictor

Name of the numeric predictor on the horizontal axis.

moderator

One or two moderator names. With raw data, moderators must be numeric. With an existing fit, they can also be categorical.

y.lim

Vertical axis limits. Defaults to c(-1, 1) for the standardized data mode and is inferred from predictions for fits.

x.lim

Horizontal axis limits. Defaults to c(-1, 1) for the standardized data mode. With a fit and no newdata, supplied limits also determine the range of the prediction grid.

x.lab, y.lab

Axis labels. Use "auto" for the variable names.

title

Plot title. Use "auto" for a title based on the variables.

title.size

Plot title size.

SDs

Number of standard deviations below and above the mean at which to draw lines for numeric moderators when no grid is supplied.

legend.name

Legend title. Use "auto" for the moderator names.

colour

High end of the colour gradient for observed points.

show.points

If TRUE, add observed points from the first completed data set. Only supported when supplying data rather than a fit.

newdata

Optional prediction grid for an existing fit. Supply one row per prediction and all required predictors on their input scales. A grid is useful for transformed formulas or custom covariate values.

Details

With data, int.plot() standardizes the outcome, predictor, and moderators within each completed data set before fitting a linear interaction. Both axes are in standard-deviation units.

With a fit, the axes use the predictor input scale and model response scale. For an autoModel, the function uses the stored training transformations, so supply raw predictor values. Without an explicit grid, the numeric predictor ranges from one SD below to one SD above its mean (unless x.lim is supplied). Lines use numeric moderator values at the mean plus or minus SDs standard deviations; with one numeric moderator, a line is also drawn at its mean. Categorical moderators use all levels. Other predictors are held at their mean or first level. For imputed fits, these defaults come from the first completed data set, and plotted predictions are averaged across fits.

An existing model is used as-is. The plot does not add an interaction term or test whether an interaction is present.

To save a figure, pass the returned plot to ggplot2::ggsave("interaction.png", plot = result$plot).

Value

A list with plot (a ggplot) and summary (the model summary). When supplying a fit, predictions contains the plotting grid with an added .prediction column.

See Also

autoModel, predict.autoModel

Examples

int.plot(mtcars, "mpg", "disp", "cyl", y.lim = c(-2.5, 2.5))$plot

fit <- glm(am ~ wt * hp, data = mtcars, family = binomial())
int.plot(fit, predictor = "wt", moderator = "hp")$plot

Predict from a selected regression model

Description

Generate point predictions on the original response scale from raw predictors, using the transformations stored by autoModel.

Usage

## S3 method for class 'autoModel'
predict(object, newdata, ..., pooled = TRUE, type = "response")

Arguments

object

A fitted autoModel object.

newdata

A data frame containing the predictors in the winning formula. Extra columns are ignored and the outcome is not required. For imputed predictions, supply either one frame to reuse across fits or one completed frame per fit, with identical row names in the same order.

...

Additional arguments to the underlying prediction method. A custom fitter's prediction method must return one numeric response prediction per row.

pooled

If TRUE, average response predictions across fits. If FALSE, keep the predictions from each fit separately.

type

Prediction scale. Only "response" is supported.

Details

Supply numeric predictors in their original units. Factor predictors may be supplied as factors or character vectors with known levels. The method applies each fit's training transformations and reverses response standardization for built-in linear models. For GLMs, the averaging is on the response scale, not the link scale.

This method returns point predictions, not standard errors or prediction intervals. It does not pool prediction uncertainty.

Value

A numeric vector in new-data row order, or, with pooled = FALSE, a matrix with one row per observation and one column per fit.

See Also

autoModel, int.plot