| mfp2 | R Documentation |
mfp2() selects predictors for a regression model and chooses a linear or
fractional-polynomial form for each selected continuous predictor. It also
supports approximate cumulative distribution (ACD) transformations for
sigmoid-shaped relationships and spike-at-zero modelling for predictors
with many exact zeros. Models can be specified with a formula and data frame
or with a numeric predictor matrix and an outcome. Both interfaces use the
same selection procedure. The formula interface is the preferred choice for
most users because it handles categorical predictors automatically; the
matrix interface requires them to be coded as numeric columns. Supported
regression models include Gaussian, binomial, Poisson, Gamma, inverse
Gaussian, negative binomial, multinomial, and ordinal models. For
time-to-event outcomes, it supports Cox, parametric survival, and Fine–Gray
competing-risks models. It also supports generalized estimating equations
(GEE) for clustered data.
mfp2(x, ...)
## Default S3 method:
mfp2(
x,
y,
weights = NULL,
offset = NULL,
cycles = 5,
scale = NULL,
shift = NULL,
df = 4,
center = TRUE,
subset = NULL,
family = gaussian(),
criterion = NULL,
select = 0.05,
alpha = 0.05,
keep = NULL,
xorder = c("ascending", "descending", "original"),
powers = NULL,
ties = c("efron", "breslow"),
strata = NULL,
nocenter = c(-1, 0, 1),
acd_vars = NULL,
ftest = FALSE,
control = NULL,
zero_vars = NULL,
catzero_vars = NULL,
spike_vars = NULL,
min_saz_prop = 0.1,
force_max_fp_vars = NULL,
term_groups = NULL,
verbose = TRUE,
fitter = c("base", "fastglm"),
id = NULL,
waves = NULL,
acdx = NULL,
...
)
## S3 method for class 'formula'
mfp2(
formula,
data,
weights = NULL,
offset = NULL,
cycles = 5,
scale = NULL,
shift = NULL,
df = 4,
center = TRUE,
subset = NULL,
family = gaussian(),
criterion = NULL,
select = 0.05,
alpha = 0.05,
keep = NULL,
xorder = c("ascending", "descending", "original"),
powers = NULL,
ties = c("efron", "breslow"),
strata = NULL,
nocenter = c(-1, 0, 1),
ftest = FALSE,
control = NULL,
min_saz_prop = 0.1,
verbose = TRUE,
fitter = c("base", "fastglm"),
id = NULL,
waves = NULL,
...
)
x |
For |
... |
Used to pass arguments from |
y |
Outcome for |
weights |
Optional numeric observation weights. All weights must
be strictly positive. In the formula interface, an expression is evaluated
first in |
offset |
A known term added to the model, such as the log of exposure
time. With formula input you can write |
cycles |
Maximum number of MFP backfitting cycles. Default |
scale |
Divisor used when preparing predictors for FP selection.
|
shift |
Value added to predictors before FP transformation.
|
df |
Maximum FP complexity: |
center |
If |
subset |
Optional observations used for model selection and fitting.
Formula calls accept an expression evaluated in |
family |
Model family; default |
criterion |
Model-selection criterion: |
select |
Significance level for predictor inclusion when
|
alpha |
Significance level for choosing between FP forms when
|
keep |
Character vector naming predictors to retain in the final
model under any selection criterion. For a formula interface, use a
predictor name from the formula, such as |
xorder |
Order in which predictors are examined during backfitting:
|
powers |
Optional named list of candidate FP powers for individual
predictors, for example |
ties |
Method for handling tied event times in Cox and Fine–Gray models.
Supported values are |
strata |
Optional stratification for Cox, parametric survival, and
Fine–Gray models. In |
nocenter |
Numeric values that exempt a Cox or Fine–Gray predictor
column from centering when every value in that column is among them.
The default, |
acd_vars |
Character vector naming continuous columns of |
ftest |
Logical. If |
control |
Optional named list of model-fitting settings. If |
zero_vars |
Names of nonnegative continuous predictors with exact zeros.
Only positive values are transformed; zeros remain zero before centering.
If a predictor is also in |
catzero_vars |
Names of nonnegative continuous predictors with exact
zeros. Positive values are transformed, and a separate indicator for zero
values is added to the model. This also enables |
spike_vars |
Names of nonnegative continuous predictors to assess with
spike-at-zero selection. The model may retain the transformed positive
values, an indicator for zeros, or both. Selection uses two-stage tests
when |
min_saz_prop |
Minimum proportion of observations required in each
group ( |
force_max_fp_vars |
Names of predictors whose most complex permitted
form should be kept in the model, regardless of the selection criterion.
The maximum is set by |
term_groups |
For |
verbose |
Logical. If |
fitter |
Backend for GLM candidate fits during the FP search.
|
id |
A subject or cluster identifier, with one value per observation.
Use the same ID for observations from the same subject or cluster. IDs
cannot be missing. Fine–Gray models require |
waves |
Optional index giving the order of repeated observations
within each |
acdx |
Deprecated compatibility alias for |
formula |
For |
data |
For |
An object of class mfp2, built from the final fitted model and extended
with MFP selection and transformation information. Depending on the model
family, it also inherits from:
glm for Gaussian, binomial, Poisson, Gamma, and inverse-Gaussian models;
fastglm_nb and fastglm for negative-binomial models;
geeglm for GEE models;
multinom and nnet for multinomial logistic models;
orm for ordinal regression models;
coxph for Cox and Fine–Gray models;
survreg for parametric survival models.
Standard fitted-model components, such as coefficients, residuals, fitted
values, and the model call, remain available. mfp2() adds the following
components to describe its selection results:
Logical value indicating whether the MFP selection algorithm converged.
A data frame with one row per model term. It records the MFP complexity
setting (df_setting) separately from the initial and final model degrees
of freedom (df_initial and df_final), together with selection settings,
selected status, searched-FP identity (searched_fp),
fractional-polynomial powers, the ACD, zero, catzero, and spike settings
actually applied after validation and eligibility checks, and prop_zero
for retained spike-at-zero terms.
A named list containing the selected fractional-polynomial powers for each model term. Terms excluded from the final model contain missing powers.
A data frame describing the shift, scale, and centering setting of each model term. The shift and centering apply to the final fitted basis; the scale is used only during FP selection, so the final basis and its coefficients use shifted, unscaled values (see Shifting, scaling, and centering).
A named logical vector indicating which terms were assessed with the ACD extension. The selected powers identify whether the final representation retained an ACD component.
A named logical vector indicating which continuous terms were transformed using only their positive values.
A named logical vector indicating which terms include a separate indicator for exact-zero values.
A named numeric vector containing the final spike-at-zero decision for
each term. A value of 1 retains both the zero indicator and continuous
component, 2 retains the continuous component only, and 3 retains
the zero indicator only. Non-spike terms use the standard value 2.
The call used to fit the model.
Use print(), summary(), coef(), predict(), and plot() for the main
model operations. Use get_selected_variable_names() to obtain the names of
terms retained in the selected model.
Only documented components form part of the stable public interface. Other components may change between package versions.
mfp2(default): Matrix interface: accepts a numeric predictor matrix x
and response vector y. Categorical predictors must be pre-coded as
numeric columns; group related columns with term_groups.
mfp2(formula): Formula interface: accepts a model formula and data frame.
Factors are expanded automatically. Use fp() or fp2() to set
variable-specific options.
For a continuous predictor x, a linear effect has the form
\beta_1 x. A first-degree fractional polynomial (FP1) replaces
x with a selected power:
\beta_1 x^{p_1}.
A second-degree fractional polynomial (FP2) uses two powers:
\beta_1 x^{p_1} + \beta_2 x^{p_2}.
By convention, a power of zero means \log(x). If the two powers
are equal, the second term is x^p\log(x); for two zero powers,
the terms are \log(x) and \{\log(x)\}^2. Here x denotes
the positive input after any shifting and scaling. The default candidate
powers are c(-2, -1, -0.5, 0, 0.5, 1, 2, 3).
The df setting limits the maximum FP degree: df = 1 allows only a
linear effect, df = 2 allows up to FP1, and the default df = 4
allows up to FP2. Higher degrees can be allowed. Predictors with only
two or three distinct values are restricted to df = 1. With four or
five distinct values, a default or global df is capped at 2, but
an explicitly set predictor-specific value is retained. Selection may
still omit a predictor or choose a simpler form. Predictors in keep
cannot be omitted, but their functional forms may still be selected.
A selected FP1 with power 1 has the same fitted basis as the fixed
linear form, but retains the FP power-search degrees of freedom. The
fp_terms$searched_fp column distinguishes these cases: TRUE means
the final continuous form came from an FP candidate class; FALSE means
it came from the fixed linear candidate or no continuous form was retained.
The flag identifies the form that won selection, not whether FP candidates
were considered. For a single-predictor term with power 1, this gives
df_final = 2 for FP1 and df_final = 1 for the fixed linear form.
With criterion = "pvalue", a closed-test-style procedure uses select
for predictor inclusion and alpha for functional-form comparisons.
With "aic" or "bic", candidate models are compared using the chosen
information criterion.
See vignette("mfp-methodology", package = "mfp2") for methodological
details.
For most users, the formula interface is the simpler choice:
mfp2(formula, data, ...). It handles factors automatically. Use fp()
or fp2() to set options for individual continuous predictors; other
predictors, including those added with ., use the applicable top-level
settings. An fp() term has its own default select = 0.05, so set
select inside the term if a different value is needed. Formulas may
also include offset() and, for survival models, strata().
The matrix interface, mfp2(x, y, ...), takes a numeric predictor
matrix. Categorical predictors must first be coded as numeric columns.
If several columns represent one predictor, use term_groups to have
them selected and tested together.
Both interfaces use the same selection procedure. Predictor names must
be unique, non-empty, and free of backticks. Names given in options such
as keep and powers must match predictors in the model.
Set family to choose the model. Standard choices are "gaussian" for
numeric outcomes, "binomial" for binary outcomes, "poisson" for counts,
and "Gamma" or "inverse.gaussian" for positive numeric outcomes.
Use negbin_family() for negative-binomial count regression with a
"log", "sqrt", or "identity" link; "negbin" is shorthand for
negbin_family(link = "log"). The first five also accept a GLM family
function or object, so you can choose a link supported by stats::glm().
Quasi families are not supported.
Binomial responses may be values from 0 to 1, a two-level factor, or a two-column matrix of success and failure counts. Poisson and negative- binomial responses must be nonnegative integer counts. Count matrices must contain at least one trial in every row.
For outcomes with at least three categories, use multinomial_family()
for unordered categories or ordinal_family() for ordered categories.
Multinomial models also accept a matrix of counts by category. See
Multinomial models and Ordinal models for response details.
For survival outcomes, use "cox" with a right-censored survival::Surv()
response, survreg_family() for parametric survival regression, or
finegray_family() for competing risks with a multi-state Surv
response. The character values "survreg" and "finegray" use the
respective default settings.
For clustered observations, use gee_family() with a Gaussian,
binomial, Poisson, or Gamma response family. The response follows the
rules for that family. See Generalized estimating equations.
Specify a GEE model with gee_family(). The required id argument
identifies clusters; the package groups their observations before fitting.
The optional waves argument specifies visit order within clusters.
gee_family() sets the response family, working correlation,
standard-error method, and scale settings. The final model is returned
as a geeglm object.
The default selection criterion for GEE models is criterion = "aic";
all other families default to criterion = "pvalue".
With criterion = "pvalue", selection uses approximate comparisons of
overall robust Wald statistics, following Stata's mfp: xtgee
calculation. During verbose fitting, the selection tables display
Wald chi-sq for candidates and Wald diff. for comparisons. The robust
covariance uses the finite-cluster correction K/(K-1), where
K is the number of clusters.
With criterion = "aic" or "bic", selection uses quasi-likelihood
scores:
-2Q/\phi + 2p \quad\text{or}\quad -2Q/\phi + \log(n)p,
respectively. Here Q is the quasi-likelihood, \phi is a single
reference dispersion shared by all comparisons, and n is the number
of clusters by default (or observations if
gee_family(qbic_penalty = "observations")).
The reference dispersion is estimated once from a full model containing all
predictors at their maximum allowed FP degrees, unless supplied through
gee_family(reference_dispersion = ...). Reference powers are fixed from
the permitted sets before the one reference fit. Geepack continues to
estimate scale for each GEE
fit; that fitted scale is used for fitting and reporting, not for these
information-criterion comparisons. p counts
mean-model coefficients, including the intercept, plus an allowance for
selecting FP powers. The first is an MFP-adjusted QICu score; the second
is a package-specific BIC-like score.
For AIC or BIC selection, print.mfp2() and summary.mfp2() show the
full-linear and selected-MFP scores under Selection Scores. Smaller
scores are preferred. For GEE p-value selection, they omit the Model Fit
block; Wald comparisons appear during verbose fitting.
FP functions involving logarithms or non-integer or negative powers need
positive inputs. By default, mfp2() adds a shift when needed and chooses
a power-of-ten scale for ordinary FP predictors to keep values numerically
manageable during selection. ACD predictors may be shifted but are not
scaled. Use shift = 0 or scale = 1 to turn off the corresponding
automatic step for ordinary FP predictors.
Predictors with exact-zero handling (zero, catzero, or spike) that
contain exact zeros are not scaled automatically (their automatic scale is
1). Their zeros stay at zero while only the positive values are
transformed, so dividing by a scale factor would add a constant to
logarithmic terms on the positive values only. That would make the
selected powers depend on the arbitrary scale factor. Without scaling, FP
selection compares the same models that are finally fitted. A scale you
supply explicitly is still used.
In mfp2.default(), a single unnamed value applies to all predictors.
A named value applies only to the specified column: for example,
shift = c(age = 20) fixes the shift for age, while shifts for other
columns are chosen automatically. The same rule applies to scale.
Do not supply NA as an explicit shift or scale value.
A supplied shift is not increased automatically. If it leaves values
nonpositive for a nonlinear FP that requires positive inputs, fitting
stops with an error. Linear predictors (df = 1) and predictors using
zero, catzero, or spike receive a shift of zero.
With center = TRUE, transformed continuous columns are centered on
their mean in the fitted sample. For a predictor with exact-zero handling,
its transformed values are set to zero at the original zeros before
this mean is subtracted. Thus, its centered values at zero need not be
zero. Binary columns have their lower observed value subtracted.
Formula-generated factor columns follow the appropriate binary or
mean-centering rule. Centering changes the intercept but not fitted values.
The final fitted FP basis uses shifted, unscaled values; scaling is used
during selection. Supply new observations to predict.mfp2() on their
original predictor scale. Prediction applies the fitted transformation
and centering settings automatically.
In the formula interface, factors are expanded into contrast columns
automatically. Each factor is selected or removed as one term. To keep a
factor, give keep its name, not the names of its contrast columns:
mfp2(y ~ age + race, data = dat, keep = "race")
Factors are not FP-transformed, and ACD and zero options do not apply to them. Ordered factors use their configured contrasts, which are polynomial by default. They are tested as a whole, rather than with a single trend test.
In the matrix interface, create the indicator or contrast columns yourself.
Use term_groups to select columns representing one categorical predictor
together. For example, if x has columns age, raceB, and raceC:
mfp2(x, y, term_groups = list(race = c("raceB", "raceC")),
keep = "race")
Here keep = "race" retains both raceB and raceC. With centering
enabled, formula-generated treatment indicators keep their zero reference;
other contrast columns are centered on their fitted-sample means. See
Shifting, scaling, and centering.
The approximate cumulative distribution (ACD) transformation can model a smooth S-shaped relationship between a continuous predictor and the outcome (Royston, 2014; Royston and Sauerbrei, 2016). It uses smoothed ranks to transform predictor values to a scale between 0 and 1.
In the matrix interface, specify predictors in acd_vars. In a formula,
use fp(x, acd = TRUE). Model selection considers ACD-based forms,
ordinary fractional polynomials, a linear effect, and exclusion of the
predictor. If the predictor has fewer than five distinct values, standard
MFP is used instead. ACD predictors may be shifted but are not scaled.
Selection uses the ACD function-selection procedure with
criterion = "pvalue"; with "aic" or "bic", candidate models are
compared using the chosen criterion.
When ACD is combined with zero = TRUE, the transformation is fitted
using positive values only; at least two distinct positive values are
required. Exact zeros receive a transformed value of zero before
centering. During prediction and plotting, positive values use the fitted
transformation, and exact zeros again receive zero before centering.
See vignette("acd-transformations", package = "mfp2") for the ACD
function-selection procedure.
Three options are available for nonnegative predictors that contain exact zeros.
zero applies the continuous transformation to positive values
only. Its value at zero is set to zero before centering.
catzero transforms positive values in the same way as zero
and adds a binary variable that equals 1 when the predictor is zero
and 0 otherwise.
spike uses the spike-at-zero selection algorithm to decide whether
the final model includes the positive-value function, the zero indicator,
both, or neither.
In the matrix interface, use zero_vars, catzero_vars, or spike_vars.
In a formula, use fp(x, zero = TRUE), fp(x, catzero = TRUE), or
fp(x, spike = TRUE). catzero includes zero handling. An eligible
spike request includes both catzero and zero handling. If ACD is
also requested, its transformation uses positive values only.
Negative values cause an error and are never treated as zeros. These
options do not apply to binary predictors. zero and catzero are
ignored if the predictor has no exact zeros.
Spike-at-zero selection requires at least min_saz_prop of observations
with zero values and at least that proportion with positive values.
The default is 0.10. If either group is too small, spike-at-zero
selection is skipped. Separately requested zero or catzero handling
remains in effect. With criterion = "pvalue", spike-at-zero selection uses
a two-stage procedure controlled by select and alpha. With
criterion = "aic" or "bic", it uses a one-stage procedure that
compares all candidate models directly. Further details on spike-at-zero
modelling are given by Kipruto and Sauerbrei (2026).
When you use subset, mfp2() determines automatic shifts and scales
from the full input data before selecting observations. Model selection
and fitting then use only the selected observations. The result may
differ from a fit where the data were subset before calling mfp2().
In the formula interface, you can select rows using a column of data.
For example, if dat has a column called group, this fits the model
using only rows where group is "A":
mfp2(y ~ age, data = dat, subset = group == "A")
In the matrix interface, supply a logical vector or unique row numbers.
The package applies the subset to x, y, weights, offset, and
strata together. Row numbers retain the order you specify.
Use subset when analyses of different groups should use shifts and
scales determined from the same full dataset. For cross-validation or
removal of missing values, prepare the analysis data before fitting.
The subset must leave more observations than predictor columns.
Cox models require a right-censored survival::Surv() response, usually
Surv(time, event) with 0 for censoring and 1 for an event. For
stratification, use strata() in a formula or the strata argument with
matrix input. The separate strata argument in the formula interface is
deprecated. Cox settings such as ties, nocenter, and control follow
survival::coxph().
Parametric survival models use survreg_family() and return a survreg
object. Here, strata allows separate scale parameters, as in
survival::survreg().
Fine–Gray models use finegray_family() with a multi-state Surv
response. By default, strata() applies to both the censoring
distribution and the baseline subdistribution hazard; change this with
strata_action. Supply id for start–stop responses; it is optional
when each subject has one row.
See predict.mfp2() for the data needed to predict survival probabilities.
Use family = "multinomial" or multinomial_family() for an outcome
with at least three unordered classes. The response can contain class
labels or be a matrix of counts, with one column per class. The first
class is the reference; use multinomial_family(reference = ...) to
choose another.
For each continuous predictor, the selected FP powers are shared across
classes, but each non-reference class has its own coefficients. Selection
degrees of freedom account for both the class-specific coefficients and
the search for shared powers. The final fit inherits from multinom.
Use ordinal_family() when the outcome has at least three categories
with a meaningful order. An ordered factor specifies that order.
Otherwise, numeric values are ordered from smallest to largest, and
character values and unordered factor levels are ordered alphabetically.
For example, to set the order of named categories:
severity <- factor(
c("low", "high", "medium", "low"),
levels = c("low", "medium", "high"),
ordered = TRUE
)
The default link = "logistic" fits a proportional-odds model. It uses
the same fitted function for each predictor when comparing higher outcome
categories with lower ones. The final fit is an orm object and requires
the optional rms package (version 7.0-0 or later). See ordinal_family()
for case weights, other links, and
how to interpret coefficient signs.
mfp packageBoth mfp and mfp2 provide fp(). In formulas passed to mfp2()
or mfpi(), fp() always uses the mfp2 version, even when both
packages are loaded. fp() and fp2() are equivalent in these formulas:
fit1 <- mfp2(y ~ fp(x1) + fp(x2), data = dat) fit2 <- mfp2(y ~ fp2(x1) + fp2(x2), data = dat)
MFP selection usually converges within 2–4 cycles. With verbose = TRUE,
progress messages report when it converges. Lack of convergence involves
oscillation between two or more models and is extremely rare. If selection
does not converge within the allowed number of cycles, mfp2()
returns the model obtained after the final cycle. Consider
increasing cycles, changing select or alpha, or using
criterion = "aic" or "bic".
Standard errors, confidence intervals, and p-values from the final model do not account for uncertainty from selecting predictors or their functional forms, including ACD and spike-at-zero selection.
Royston, P. and Sauerbrei, W., 2008. Multivariable Model - Building:
A Pragmatic Approach to Regression Analysis based on Fractional Polynomials
for Modelling Continuous Variables. John Wiley & Sons.
Liang, K.-Y. and Zeger, S. L., 1986. Longitudinal data analysis using
generalized linear models. Biometrika, 73(1): 13–22.
Pan, W., 2001. Akaike's information criterion in generalized
estimating equations. Biometrics, 57(1): 120–125.
Sauerbrei, W., Meier-Hirmer, C., Benner, A. and Royston, P., 2006.
Multivariable regression model building by using fractional
polynomials: Description of SAS, STATA and R programs.
Comput Stat Data Anal, 50(12): 3464-85.
Royston, P. 2014. A smooth covariate rank transformation for use in
regression models with a sigmoid dose-response function.
Stata Journal 14(2): 329-341.
Royston, P. and Sauerbrei, W., 2016. mfpa: Extension of mfp using the
ACD covariate transformation for enhanced parametric multivariable modeling.
The Stata Journal, 16(1), pp.72-87.
Sauerbrei, W. and Royston, P., 1999. Building multivariable prognostic
and diagnostic models: transformation of the predictors by using fractional
polynomials. J Roy Stat Soc a Sta, 162:71-94.
Sauerbrei, W., Kipruto, E. and Balmford, J., 2023. Effects of influential
points and sample size on the selection and replicability of multivariable
fractional polynomial models. Diagnostic and Prognostic Research, 7(1), p.7.
Becher, H., Lorenz, E., Royston, P. and Sauerbrei, W., 2012. Analysing
covariates with spike at zero: a modified FP procedure and conceptual issues.
Biometrical journal, 54(5), pp.686-700.
Lorenz, E., Jenkner, C., Sauerbrei, W. and Becher, H., 2019. Modeling exposures with a spike at zero: simulation study and practical application to survival data. Biostatistics & Epidemiology, 3(1), pp.23-37.
fp(), fp2(), summary.mfp2(), coef.mfp2(), predict.mfp2(),
plot.mfp2(), get_selected_variable_names(), transform_vector_fp(),
gee_family(), multinomial_family(), ordinal_family(),
survreg_family(), finegray_family()
# Gaussian model: formula interface (recommended for most users)
data("prostate")
fit_formula <- mfp2(
lpsa ~ fp(age) + fp(svi, df = 1) + fp(pgg45) + fp(cavol) +
fp(weight) + fp(bph) + fp(cp),
data = prostate,
verbose = FALSE
)
fit_formula
summary(fit_formula)
get_selected_variable_names(fit_formula)
if (requireNamespace("ggplot2", quietly = TRUE)) {
plots <- plot(fit_formula)
print(plots[[1]])
}
predict(fit_formula, newdata = prostate[1:5, ])
# Matrix interface
x <- as.matrix(prostate[, 2:8])
y <- prostate$lpsa
fit_matrix <- mfp2(x, y, verbose = FALSE)
fit_matrix
# Named partial settings apply only to the named columns. Here age is fixed,
# while shifts and scales for every other matrix column remain automatic.
fit_partial <- mfp2(
x,
y,
shift = c(age = 20),
scale = c(age = 10),
verbose = FALSE
)
fit_partial$transformations[c("age", "weight"), c("shift", "scale")]
# ACD modelling
fit_acd_formula <- mfp2(
lpsa ~ fp(cavol, acd = TRUE) + fp(age) + svi,
data = prostate,
verbose = FALSE
)
if (requireNamespace("ggplot2", quietly = TRUE)) {
plot(fit_acd_formula, terms = "cavol")[[1]]
}
# Spike-at-zero modelling
set.seed(1)
n <- 200
exposure <- numeric(n)
zero_rows <- sample(seq_len(n), size = round(0.25 * n))
exposure[-zero_rows] <- rgamma(
n - length(zero_rows),
shape = 2,
rate = 0.5
)
age <- runif(n, 20, 80)
outcome <- 1.5 * (exposure == 0) +
2 * log(ifelse(exposure > 0, exposure, 1)) +
0.02 * age + rnorm(n)
d_spike <- data.frame(outcome, exposure, age)
# Formula interface
fit_spike_formula <- mfp2(
outcome ~ fp(exposure, spike = TRUE) + fp(age),
data = d_spike,
verbose = FALSE
)
if (requireNamespace("ggplot2", quietly = TRUE)) {
plot(fit_spike_formula, terms = "exposure")[[1]]
}
# Matrix interface
x_spike <- as.matrix(d_spike[, c("exposure", "age")])
fit_spike_matrix <- mfp2(
x_spike,
d_spike$outcome,
spike_vars = "exposure",
verbose = FALSE
)
# Unordered factor: all treatment-contrast columns are selected jointly
set.seed(42)
d_factor <- data.frame(
y = rnorm(60),
age = runif(60, 20, 80),
group = factor(rep(c("A", "B", "C"), each = 20))
)
fit_factor <- mfp2(
y ~ age + group,
data = d_factor,
keep = "group",
verbose = FALSE
)
predict(fit_factor, newdata = d_factor[1:4, ])
# Ordered factor: the default polynomial contrasts form one joint term
d_factor$severity <- ordered(
rep(c("mild", "moderate", "severe"), length.out = nrow(d_factor)),
levels = c("mild", "moderate", "severe")
)
fit_ordered <- mfp2(
y ~ age + severity,
data = d_factor,
keep = "severity",
verbose = FALSE
)
predict(
fit_ordered,
newdata = data.frame(
age = c(40, 40),
severity = ordered(
c("mild", "severe"),
levels = levels(d_factor$severity)
)
)
)
# Matrix interface: manually created dummy columns can be grouped as one term
x_grouped <- cbind(
age = d_factor$age,
groupB = as.integer(d_factor$group == "B"),
groupC = as.integer(d_factor$group == "C")
)
fit_grouped <- mfp2(
x_grouped,
d_factor$y,
term_groups = list(group = c("groupB", "groupC")),
keep = "group",
verbose = FALSE
)
# Examples for every supported model family -----------------------------
set.seed(2026)
n_family <- 120
family_data <- data.frame(
x1 = runif(n_family, 0.5, 3),
x2 = rnorm(n_family)
)
eta <- with(family_data, 0.2 + 0.3 * x1 - 0.2 * x2)
mu <- exp(eta)
simulate_inverse_gaussian <- function(mu, shape) {
squared_normal <- stats::rnorm(length(mu))^2
candidate <- mu + (mu^2 * squared_normal) / (2 * shape) -
(mu / (2 * shape)) * sqrt(
4 * mu * shape * squared_normal + mu^2 * squared_normal^2
)
choose_candidate <- stats::runif(length(mu)) <= mu / (mu + candidate)
ifelse(choose_candidate, candidate, mu^2 / candidate)
}
family_data$y_gaussian <- eta + rnorm(n_family)
family_data$y_binomial <- rbinom(n_family, 1, plogis(eta - 1))
family_data$y_poisson <- rpois(n_family, mu)
family_data$y_gamma <- rgamma(n_family, shape = 5, scale = mu / 5)
family_data$y_inverse_gaussian <- simulate_inverse_gaussian(mu, shape = 8)
family_data$y_negbin <- rnbinom(n_family, mu = mu, size = 2)
family_data$y_multinomial <- sample.int(
3L, n_family, replace = TRUE, prob = c(0.45, 0.35, 0.20)
)
family_data$y_ordinal <- ordered(
cut(
eta + stats::rlogis(n_family),
breaks = c(-Inf, -0.5, 0.5, 1.5, Inf),
labels = c("low", "medium", "high", "very high")
)
)
fit_gaussian <- mfp2(
y_gaussian ~ x1 + x2, data = family_data, family = "gaussian",
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
fit_binomial <- mfp2(
y_binomial ~ x1 + x2, data = family_data, family = "binomial",
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
fit_poisson <- mfp2(
y_poisson ~ x1 + x2, data = family_data, family = "poisson",
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
fit_gamma <- mfp2(
y_gamma ~ x1 + x2, data = family_data,
family = stats::Gamma(link = "log"),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
fit_inverse_gaussian <- mfp2(
y_inverse_gaussian ~ x1 + x2, data = family_data,
family = stats::inverse.gaussian(link = "log"),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
# Negative binomial uses the optional fastglm backend. `"negbin"` is
# shorthand for negbin_family(link = "log"); see ?negbin_family for the
# square-root and identity links.
if (requireNamespace("fastglm", quietly = TRUE)) {
fit_negbin <- mfp2(
y_negbin ~ x1 + x2, data = family_data,
family = "negbin",
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
}
# Integer class labels are converted to a multinomial factor response.
fit_multinomial <- mfp2(
y_multinomial ~ x1 + x2, data = family_data,
family = multinomial_family(),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
# Ordinal regression uses the optional rms package.
if (requireNamespace("rms", quietly = TRUE) &&
utils::packageVersion("rms") >= "7.0-0") {
fit_ordinal <- mfp2(
y_ordinal ~ x1 + x2, data = family_data,
family = ordinal_family(),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
}
# Cox proportional hazards and parametric survival models.
event_time <- rexp(n_family, rate = exp(eta - 2))
censor_time <- rexp(n_family, rate = 0.15)
survival_data <- transform(
family_data,
time = pmin(event_time, censor_time),
status = as.integer(event_time <= censor_time)
)
fit_cox <- mfp2(
survival::Surv(time, status) ~ x1 + x2,
data = survival_data, family = "cox",
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
fit_survreg <- mfp2(
survival::Surv(time, status) ~ x1 + x2,
data = survival_data, family = survreg_family(dist = "weibull"),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
# Fine--Gray subdistribution hazards for a competing-risks response.
finegray_data <- transform(
family_data,
ftime = rexp(n_family, rate = 0.12),
event = factor(
sample(
c("censor", "cause1", "cause2"), n_family, replace = TRUE,
prob = c(0.35, 0.40, 0.25)
),
levels = c("censor", "cause1", "cause2")
)
)
fit_finegray <- mfp2(
survival::Surv(ftime, event) ~ x1 + x2,
data = finegray_data, family = finegray_family(etype = "cause1"),
df = 1, select = 1, alpha = 1, cycles = 1, verbose = FALSE
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.