| f_lm | R Documentation |
lm() functions with optional data transformation, inspection, regression plots and post hoc test.Performs ordinary least squares linear regression (stats::lm) on a
given dataset with options for (Box-Cox) transformations, normality tests,
regression plots, and post hoc analysis for categorical predictors. Several
response parameters can be analysed in sequence and the generated output can
be in various formats ('Word', 'pdf', 'Excel').
f_lm(
formula,
data = NULL,
norm_plots = TRUE,
effect_plots = TRUE,
contrast_plots = FALSE,
transformation = TRUE,
force_transformation = NULL,
alpha = 0.05,
adjust = "sidak",
intro_text = TRUE,
close_generated_files = FALSE,
open_generated_files = interactive(),
output_type = "default",
save_as = NULL,
save_in_wdir = FALSE,
...
)
formula |
A formula specifying the model to be fitted. More response variables can be added using |
data |
A data frame containing the variables in the model. |
norm_plots |
Logical. If |
effect_plots |
Logical. If |
contrast_plots |
Logical. If |
transformation |
Logical or character string. If |
force_transformation |
Character string. A vector containing the names of response variables that should be transformed regardless of the normality test. Default is |
alpha |
Numeric. Significance level for tests, post hoc comparisons, and Shapiro-Wilk test. Default is |
adjust |
Character string specifying the method used to adjust p-values for multiple comparisons. Available methods include:
Default is |
intro_text |
Logical. If |
close_generated_files |
Logical. Closes open Excel or Word (NOT pdf) files before writing, depending on the output format. Works on Windows (taskkill), macOS (pkill) and Linux (pkill/soffice). Default |
open_generated_files |
Logical. Whether to open the generated output
files after creation. Defaults to |
output_type |
Character string specifying the output format. Default is
|
save_as |
Character string specifying the output file path (without extension).
If a full path is provided, output is saved to that location.
If only a filename is given, the file is saved in |
save_in_wdir |
Logical. If |
... |
Additional arguments forwarded to |
f_lm() is the regression sibling of f_aov: it shares the
same assumption checks (Shapiro-Wilk, Anderson-Darling, Levene / Breusch-Pagan),
the same optional Box-Cox / bestNormalize transformation workflow, the same
object structure, and the same shared publication theme
(f_theme_pub()) and palette (f_pub_palette()). Where
f_aov() converts all predictors to factors, f_lm() keeps numeric
predictors numeric so they are modelled as continuous regression terms, and
it adds regression-specific output: a coefficient table, a coefficient forest
plot, a Type II Analysis of Variance table, the overall R^2 / adjusted
R^2 / model F-test, and regression plots (see Details).
The function performs the following steps:
Check if all specified variables are present in the data.
Ensure that the response variable is numeric.
Fit a linear model using the specified formula and data. Numeric predictors are kept numeric (continuous regression terms); character and logical predictors are converted to factors.
Check normality of the residuals using the Shapiro-Wilk and
Anderson-Darling tests, and homoscedasticity using a Breusch-Pagan test
(rstatix / car style) on the model residuals.
If residuals are not normal and transformation = TRUE apply a
data transformation and refit.
Report the coefficient table, a coefficient forest plot, a Type II
Analysis of Variance table, and the overall model fit (R^2,
adjusted R^2, F-statistic).
For categorical predictors, if significant effects are found, post hoc
tests use estimated marginal means from emmeans() with the chosen
adjustment, summarised with a compact letter display.
Regression and effect plots. When effect_plots = TRUE the
following figures are produced (the current de facto standard for visualising
a multiple-regression model):
Coefficient forest plot (always, when there is more than an
intercept): one row per coefficient with its Wald confidence interval and
a reference line at zero. This is the standard way to read a model with
many predictors at a glance and scales to any number of terms. Stored as
out$y1$coef_forest_plot.
Partial-effect (adjusted prediction) plots for each
continuous predictor: the model-predicted response across the range of
that predictor, with the other predictors held at their mean (numeric) or
reference level (factor), shown with a confidence band and a rug / scatter
of the raw data. These are computed from the fitted model via
emmeans::emmip() (equivalent to the effects / ggeffects
standard) so the lines are consistent with the rest of the report. Stored
as out$y1$effect_plot_<predictor>.
Estimated-means plots for each categorical predictor
(estimate \pm CI, jittered raw data, compact-letter-display
labels), matching f_aov. Stored as
out$y1$effect_plot_<predictor>.
Slope plots for a significant numeric \times
categorical interaction: a scatter of the raw data with one model-fitted
regression line per factor level and a confidence band (the lines are not
parallel when the interaction is significant), matching
f_lmer. Stored as
out$y1$interaction_plot_<num>_<fac>.
Categorical interaction plots (2-, 3-, 4-way) when a
significant categorical interaction is present, matching
f_aov.
Observed-versus-fitted plot: observed response against the
model fitted values with a 1:1 reference line, a quick visual of overall
fit. Stored as out$y1$obs_fitted_plot.
All plots are ggplot2 objects stored in the returned object so they can
be retrieved and customised, and plot() re-prints them so the
interactive output matches the report output.
When the response was transformed (Box-Cox or bestNormalize), the post hoc
estimates are back-transformed to the original scale (medians), exactly as in
f_aov.
Outputs can be generated in multiple formats ("pdf", "word", "excel" and "rmd") as specified by output_type. If output_type = "rmd" is used it is advised to use it in a chunk with {r, echo=FALSE, results='asis'}.
This function requires [Pandoc](https://github.com/jgm/pandoc/releases/tag) (version 1.12.3 or higher), a universal document converter.
An object of class 'f_lm' containing results from lm(), normality tests, transformations, coefficient tables, Type II ANOVA, and post hoc tests. Using the option "output_type", it can also generate output in the form of: R Markdown code, 'Word', 'pdf', or 'Excel' files. Includes print and plot methods for 'f_lm' objects.
When several response variables are analysed in a single call
(e.g. y1 + y2 + y3 ~ x), each regression is an independent
null-hypothesis test at level alpha. The post hoc adjustments only
control the family-wise error rate within one model. They do
not protect against the inflation of Type I error across
the set of responses. With k independent responses all tested at
\alpha = 0.05, the probability of at least one false positive is
1 - (1 - 0.05)^k. Consider a Bonferroni (alpha = 0.05 / k) or
FDR correction across responses, or pre-registration of primary outcomes.
Sander H. van Delden plantmind@proton.me
# Continuous predictor: simple linear regression.
f_lm_out <- f_lm(Sepal.Length ~ Petal.Length, data = iris)
print(f_lm_out)
plot(f_lm_out)
# Mixed continuous + categorical predictors (ANCOVA-style multiple regression).
iris$Species <- factor(iris$Species)
f_lm(Sepal.Length ~ Petal.Length + Species, data = iris, output_type = "word")
# Two responses analysed in sequence, captured in one output file.
f_lm(Sepal.Width + Sepal.Length ~ Petal.Length * Species,
effect_plots = FALSE,
norm_plots = FALSE,
data = iris)
# To print rmd output set chunk option to results = 'asis' and use cat().
f_lm_rmd_out <- f_lm(Sepal.Length ~ Petal.Length, data = iris, output_type = "rmd")
cat(f_lm_rmd_out$rmd)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.