matrix_to_formula: Convert a matrix-based model to a formula interface

View source: R/interface_to_interface.R

matrix_to_formulaR Documentation

Convert a matrix-based model to a formula interface

Description

Wraps a model function that expects a numeric matrix X and a response vector y (like glmnet::glmnet) so it can be called with the familiar formula + data interface. The formula is expanded via model.matrix, which handles factor dummy-coding, interactions, and inline transformations automatically.

Usage

matrix_to_formula(
  fit_func,
  predict_func = function(model, newX, ...) stats::predict(model, newdata = newX, ...)
)

Arguments

fit_func

A model-fitting function whose first two positional arguments are x (numeric matrix) and y (response vector), e.g. glmnet::glmnet.

predict_func

A prediction function with signature function(model, newX, ...) where newX is a numeric matrix. Defaults to a thin wrapper around stats::predict that passes newdata as newx.

Value

A named list with two elements:

fit(formula, data, ...)

Fits the model. The formula is expanded with model.matrix; the intercept column is dropped before passing to fit_func (add it back via ... if your model needs it). Extra arguments are forwarded to fit_func.

predict(model, newdata, ...)

Generates predictions. newdata is expanded with the same model.matrix terms captured at fit time. Extra arguments are forwarded to predict_func.

Examples

## Not run: 
glmnet_formula <- matrix_to_formula(
  fit_func = glmnet::glmnet,
  predict_func = function(model, newX, ...) {
    glmnet::predict.glmnet(model, newx = newX, s = 0.01, ...)
  }
)
model <- glmnet_formula$fit(mpg ~ wt + hp + factor(cyl), data = mtcars)
glmnet_formula$predict(model, newdata = mtcars[1:5, ])

## End(Not run)


unifiedml documentation built on April 3, 2026, 5:06 p.m.