f_lm: Perform multiple 'lm()' functions with optional data...

View source: R/flm.R

f_lmR Documentation

Perform multiple lm() functions with optional data transformation, inspection, regression plots and post hoc test.

Description

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').

Usage

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,
  ...
)

Arguments

formula

A formula specifying the model to be fitted. More response variables can be added using - or + (e.g., response1 + response2 ~ predictor) to do a sequential lm() for each response parameter.

data

A data frame containing the variables in the model.

norm_plots

Logical. If TRUE, diagnostic residual plots are included in the output files. Default is TRUE.

effect_plots

Logical. If TRUE, regression / effect plots are included in the output files after the post hoc table. See Details for what is drawn and how the plots are stored. Default is TRUE.

contrast_plots

Logical. If TRUE, a contrast forest plot is added for each categorical post hoc term: one row per pairwise comparison, showing the estimated difference between two levels with its confidence interval and a reference line at zero. A CI that excludes zero indicates a significant difference. Default FALSE because the number of pairwise contrasts grows quickly with the number of factor levels (k levels give k(k-1)/2 contrasts). Main-effect contrast plots are stored as out$y1$contrast_plot_<term> and interaction cell-contrast plots as out$y1$interaction_contrast_plot_<term>. Contrast CIs use the same adjust method as the post hoc p-values, so figure and table agree.

transformation

Logical or character string. If TRUE, or if "boxcox" applies an f_boxcox() transformation if residuals are not normal. If "bestnormalize", applies f_bestNormalize() transformation. If FALSE no transformation will be applied. Default is TRUE.

force_transformation

Character string. A vector containing the names of response variables that should be transformed regardless of the normality test. Default is NULL.

alpha

Numeric. Significance level for tests, post hoc comparisons, and Shapiro-Wilk test. Default is 0.05.

adjust

Character string specifying the method used to adjust p-values for multiple comparisons. Available methods include:

"tukey"

Tukey's Honest Significant Difference method.

"sidak"

Sidak correction.

"bonferroni"

Bonferroni correction.

"none"

No adjustment.

"fdr"

False Discovery Rate adjustment.

Default is "sidak".

intro_text

Logical. If TRUE, includes a short explanation about linear regression assumptions in the output file. Default is TRUE.

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 FALSE. WARNING: Always save your work before using this option!!

open_generated_files

Logical. Whether to open the generated output files after creation. Defaults to TRUE in an interactive R session and FALSE otherwise (e.g. in scripts or automated pipelines).

output_type

Character string specifying the output format. Default is "default".

  • "default": Returns the object and lets R decide whether to print; auto-prints if unassigned, silent if assigned to a variable.

  • "console": Forces immediate printing to the console.

  • "pdf", "word", "excel": Saves results to a file of the corresponding format.

  • "rmd": Stores the raw markdown string inside the returned object for use in R Markdown documents.

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 tempdir(). If only a directory is specified (existing directory with trailing slash), the file is named "dataname_lm_output" in that directory. If an extension is provided the output format specified with option "output_type" will be overruled.

save_in_wdir

Logical. If TRUE, saves the file in the working directory. Default is FALSE. If save_as location is specified save_in_wdir is overwritten by save_as.

...

Additional arguments forwarded to lm. The arguments subset and weights are handled specially: when supplied, they are applied via model.frame so that the Shapiro-Wilk test, Levene/Breusch-Pagan test, optional transformations, residual diagnostics, and emmeans post hoc tests all see the exact same row set as lm() itself.

Details

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.

Value

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.

Multiple Testing Across Response Variables

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.

Author(s)

Sander H. van Delden plantmind@proton.me

Examples

# 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)



rfriend documentation built on July 7, 2026, 1:06 a.m.