f_glm: Perform multiple 'glm()' functions with diagnostics,...

View source: R/fglm.R

f_glmR Documentation

Perform multiple glm() functions with diagnostics, assumption checking, and post hoc analysis

Description

Performs Generalized Linear Model (GLM) analysis on a given dataset with options for diagnostics, assumption checking, and post hoc analysis. Several response parameters can be analyzed in sequence and the generated output can be in various formats ('Word', 'pdf', 'Excel').

Usage

f_glm(
  formula,
  family = gaussian(),
  data = NULL,
  diagnostic_plots = TRUE,
  effect_plot = TRUE,
  contrast_plots = FALSE,
  alpha = 0.05,
  adjust = "sidak",
  type = "response",
  intro_text = TRUE,
  dispersion_test = TRUE,
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  influence_threshold = 2,
  ...
)

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 GLM for each response parameter.

family

The error distribution and link function to be used in the model (default: gaussian()). This can be a character string naming a family function, a family function or the result of a call to a family function. (See family for details of family functions.)

data

A data frame containing the variables in the model.

diagnostic_plots

Logical. If TRUE, plots are included in the output files.

effect_plot

Logical. If TRUE (default), estimated marginal means plots (or interaction plots, when a categorical interaction is significant) are added after the post hoc table. See Details for what is drawn and how the plots are stored.

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; because the interval is on the difference itself, this "excludes zero" reading is exact (it is the same information the compact-letter display encodes, but it also shows the direction and magnitude of each 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); turn it on when you want the detailed pairwise picture. 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. The contrasts are computed on the link (model) scale, where differences are additive and symmetric.

alpha

Numeric. Significance level for tests. 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".

type

Character string specifying the scale of emmeans post hoc results: "response" (back-transformed to original units, e.g. probabilities, counts) or "link" (on the linear predictor scale, e.g. log-odds). Default is "response".

intro_text

Logical. If TRUE, includes a short explanation about GLM assumptions in the output file.

dispersion_test

Logical. If TRUE, includes a dispersion diagnostic section in the output: a DHARMa simulation-based test for overdispersion (Poisson/Binomial), the quasi-dispersion parameter (quasi-families), or a note explaining why the test is skipped (Bernoulli data). Default is TRUE.

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. Use print(result) or plot(result) to display the returned object.

  • "console": Forces immediate printing to the console regardless of object assignment.

  • "pdf", "word", "excel": Saves results to a file of the corresponding format. See save_as, save_in_wdir, and open_generated_files for file path and opening behavior.

  • "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 (providing an existing directory with trailing slash), the file is named "dataname_glm_output" in that directory. If an extension is provided the output format specified with option "output_type" will be overruled. Defaults to file.path(tempdir(), "dataname_summary.pdf").

save_in_wdir

Logical. If TRUE, saves the file in the working directory. Default is FALSE, this avoid unintended changes to the global environment. If save_as location is specified save_in_wdir is overwritten by save_as.

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). Set to TRUE or FALSE to override this behaviour explicitly.

influence_threshold

Numeric multiplier for the leverage threshold. Observations with hat values exceeding influence_threshold * mean(hat values) are flagged as high-leverage points. Default is 2, a common rule of thumb.

...

Additional arguments passed to glm().

Details

The function first checks if all specified variables are present in the data and ensures that the response variable is numeric.

It fits a Generalized Linear Model (GLM) using the specified formula, family, and data. Model diagnostics are performed with DHARMa (simulation-based residual checks including a KS test, dispersion test, and outlier test). High-leverage observations are flagged using hat values.

Significance of each predictor is assessed via Type II Analysis of Deviance (stats::drop1()). If significant effects are found, post hoc pairwise comparisons are performed using estimated marginal means from emmeans() with the chosen p-value adjustment method (default: Sidak). When complete separation is detected, the function falls back to likelihood ratio test (LRT) based pairwise comparisons, which are robust to separation.

Effect and interaction plots. When effect_plot = TRUE, an estimated marginal means plot (estimate \pm 95% CI on the response scale, with jittered raw data and compact-letter-display labels) is added after the post hoc table for each categorical predictor. For a significant categorical interaction, interaction plots are drawn instead: a two-way interaction uses the x-axis plus colour (both orientations), while three- and four-way interactions add facet panels for the remaining factor(s), with one plot per choice of x-axis factor. Interactions involving five or more categorical factors are not plotted (a warning is issued); consult the post hoc cell-means table instead. Estimates follow the type argument, so for non-gaussian families they are back-transformed to the response scale. The plots themselves are kept clean for publication (data, axes, and legend only); the descriptive label and explanatory caption are emitted as text above and below each figure in the report. All effect and interaction plots are ggplot2 objects and are stored in the returned object (e.g. out$y1$effect_plot_treatment, out$y1$interaction_plot_a_b_1) so they can be retrieved and customised afterwards. Matches f_aov.

More response variables can be added using + (e.g., response1 + response2 ~ predictor) to fit a sequential GLM for each response variable, captured in one output file.

Outputs can be generated in multiple formats ("pdf", "word", "excel" and "rmd") as specified by output_type. The function also closes any open 'Word' files to avoid conflicts when generating 'Word' documents. 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.

  • Windows: Install Pandoc and ensure the installation folder
    (e.g., "C:/Users/your_username/AppData/Local/Pandoc") is added to your system PATH.

  • macOS: If using Homebrew, Pandoc is typically installed in "/usr/local/bin". Alternatively, download the .pkg installer and verify that the binary's location is in your PATH.

  • Linux: Install Pandoc through your distribution's package manager (commonly installed in "/usr/bin" or "/usr/local/bin") or manually, and ensure the directory containing Pandoc is in your PATH.

  • If Pandoc is not found, this function may not work as intended.

Value

An object of class 'f_glm' (a named list, one entry per response variable) containing:

model

The fitted glm object.

summary

Output of summary(glm_fit).

drop1

Type II Analysis of Deviance table from stats::drop1().

diagnostics

DHARMa residual checks and hat-value based leverage diagnostics.

posthoc

Estimated marginal means, pairwise comparisons, CLD letters, and summary table.

sep_flag

Logical indicating whether complete separation was detected.

lrt_pct_explained

McFadden's Pseudo-R^2.

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_glm' objects.

Author(s)

Sander H. van Delden plantmind@proton.me

Examples


# GLM Binomial example with output to console
mtcars_mod <- mtcars
mtcars_mod$cyl <- as.factor(mtcars_mod$cyl)

glm_bin <- f_glm(vs ~ cyl,
                 family = binomial,
                 data = mtcars_mod,
                 output_type = "default")
print(glm_bin)

# GLM Binomial example with output to MS Word file
glm_bin_word <- f_glm(vs ~ cyl,
                 family = binomial,
                 data = mtcars_mod,
                 output_type = "word"
                 )

# GLM Poisson example with output to rmd text
data(warpbreaks)

glm_pos <- f_glm(breaks ~ wool + tension,
                 data = warpbreaks,
                 family = poisson(link = "log"),
                 intro_text = FALSE,
                 output_type = "rmd")
cat(glm_pos$rmd)



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