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

View source: R/interface_to_interface.R

formula_to_matrixR Documentation

Convert a formula-based model to a matrix interface

Description

Wraps a model function that expects formula + data so it can be called with a plain X (data.frame or matrix) and y (vector). Factors in X are preserved; special column names are safely backtick-quoted in the generated formula so they survive the formula parser.

Usage

formula_to_matrix(fit_func, predict_func = stats::predict)

Arguments

fit_func

A model-fitting function whose first two arguments are formula and data (e.g. lm, glm).

predict_func

A prediction function with signature function(model, newdata, ...). Defaults to stats::predict.

Value

A named list with two elements:

fit(X, y, weights, ...)

Fits the model. X is a data.frame (or coercible matrix), y is the response vector. Extra arguments are forwarded to fit_func.

predict(model, newdata, ...)

Generates predictions. newdata must have the same columns as the X used in fit. Extra arguments are forwarded to predict_func.

Examples

lm_matrix <- formula_to_matrix(lm)
X <- data.frame(wt = mtcars$wt, hp = mtcars$hp, cyl = factor(mtcars$cyl))
y <- mtcars$mpg
model <- lm_matrix$fit(X, y)
lm_matrix$predict(model, X[1:5, ])


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