ggeffects

repository·master·Indexed 20 days ago

https://github.com/strengejacke/ggeffects

An R package for calculating Estimated Marginal Means and Adjusted Predictions from regression models. It provides a consistent way to interpret complex models by visualizing how predictors relate to the response variable on the response scale. Key functions include predict_response() for calculating predictions, plot() for visualization, and test_predictions() for checking statistically significant differences. The package supports a wide range of models, including lm, glm, lmerMod, and brmsfit.

Tokens
3.7K
Snippets
8
Records
14
Agent score
69%

What's inside ggeffects

  1. Understand the ggeffects workflow

    master

    The ggeffects package is designed to help you understand how predictors and outcomes are related using model-based estimates (adjusted predictions). The typical workflow consists of three core functions:

    1. predict_response(): Calculate adjusted predictions or estimated marginal means for your focal terms (the predictors you are interested in).
    2. plot(): Visualize the results with publication-ready figures.
    3. test_predictions(): Check for statistically significant differences (contrasts or pairwise comparisons).

    All functions are type-safe and return data frames with a consistent structure, making them ready for use with ggplot2.

  2. Understand the consistent output structure of ggeffects

    master

    All functions in ggeffects return data frames with a consistent, tidy structure regardless of the model type. This allows for easy integration into automated workflows. The standard columns include:

    • x: The values for the predictor on the x-axis.
    • predicted: The predicted values of the response.
    • conf.low: The lower bound of the confidence interval.
    • conf.high: The upper bound of the confidence interval.
    • group: A factor used for grouping (when multiple terms are provided).
  3. How `predict_response()` marginalizes over non-focal predictors

    master

    When using predict_response(), you specify focal terms (the predictors of interest) via the terms argument. All other predictors (non-focal terms) are marginalized over. The margin argument determines how this marginalization occurs:

    • "mean_reference" or "mean_mode": Non-focal predictors are set to a single 'typical' value (mean for numeric, reference level or mode for factors). This answers: "What is the predicted value for a 'typical' observation?"
    • "marginalmeans": Non-focal predictors are marginalized over their levels/values (e.g., a weighted average for factors). This answers: "What is the predicted value for an 'average' observation in my data?"
    • "empirical" (aliases: "counterfactual", "average"): Non-focal predictors are marginalized over the actual observations in your sample. This answers: "What is the predicted value for the 'average' observation in the population?"

    Note: Predictions are always returned on the response scale, which is the most intuitive scale for interpretation.

  4. Migrate from ggeffects to modelbased

    master

    The ggeffects package is currently in maintenance mode. While existing code using predict_response(), ggpredict(), or plot() will continue to work, new features will be developed in the modelbased package.

    When to switch:

    • If you only use predict_response(), ggpredict(), or plot(), you do not need to change anything.
    • If you want to leverage advanced features like estimating marginal effects (not just adjusted predictions), contrasts, or pairwise comparisons, it is recommended to switch to modelbased.
  5. Visualize marginal effects using ggplot2 or the plot() method

    master

    There are two main ways to visualize the results from ggpredict():

    1. Manual ggplot2: Since ggpredict() returns a tidy data frame, you can use standard ggplot2 aesthetics. The columns x and predicted map to the x and y axes, conf.low and conf.high are used for confidence ribbons, and group can be used for grouping or faceting.

    2. The plot() method: ggpredict() objects have a plot() method that automatically handles common plot characteristics (like axis labels and dodging) and returns a ggplot object.

    # Option 1: Manual ggplot2
    library(ggplot2)
    mydf <- ggpredict(fit, terms = "c12hour")
    ggplot(mydf, aes(x, predicted)) +
      geom_line() +
      geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .1)
    
    # Option 2: Built-in plot method
    p <- ggpredict(fit, terms = c("c172code", "c161sex"))
    plot(p)
  6. Install ggeffects

    master

    You can install ggeffects from CRAN for the stable release, or use r-universe or GitHub for development versions.

    TypeSourceCommand
    ReleaseCRANinstall.packages("ggeffects")
    Developmentr - universeinstall.packages("ggeffects", repos = "https://strengejacke.r-universe.dev")
    DevelopmentGitHubremotes::install_github("strengejacke/ggeffects")

    You can also use ggeffects::install_latest() to install the latest development version from r-universe.

    # Install stable release from CRAN
    install.packages("ggeffects")
    
    # Install development version from r-universe
    install.packages("ggeffects", repos = "https://strengejacke.r-universe.dev")
    
    # Install development version from GitHub
    remotes::install_github("strengejacke/ggeffects")
  7. Note on Maintenance Mode and modelbased

    master

    The ggeffects package is currently in maintenance mode. While core functions like predict_response(), ggpredict(), and plot() will continue to work and be maintained for bugs, new feature development is moving to the modelbased package.

    When to switch to modelbased:

    • If you need to estimate marginal effects (not just adjusted predictions).
    • If you want to leverage the latest features for contrasts and pairwise comparisons.
    • If you want a more modern, intuitive user interface for the easystats ecosystem.
  8. Calculate adjusted predictions for several focal predictors

    master

    To explore interactions or multiple predictors, pass a vector of terms to the terms argument in predict_response(). You can provide up to four terms.

    When multiple terms are provided, the resulting data frame includes a group column and a facet column, which can be used for grouping aesthetics or faceting in ggplot2. This allows you to visualize how the effect of one predictor changes across levels of others.

    library(ggeffects)
    # ... (setup fit as in previous example)
    
    # Predict for multiple terms
    result <- predict_response(fit, terms = c("neg_c_7", "c161sex", "e42dep"))
    
    # Print with collapsed table for readability
    print(result, collapse_table = TRUE, collapse_ci = TRUE)
    
    # Plotting with faceting
    library(ggplot2)
    ggplot(result, aes(x = x, y = predicted, colour = group)) +
      geom_line() +
      facet_wrap(~facet)
  9. Calculate adjusted predictions for one focal predictor

    master

    Use predict_response() to calculate predicted values for a single term. The terms argument specifies the focal predictor. The function returns a data frame with a consistent structure:

    • x: values for the x-axis
    • predicted: predicted values for the y-axis
    • conf.low and conf.high: lower and upper confidence bounds
    • group: grouping variable (if multiple terms are provided)

    You can visualize these results using the built-in plot() method or by manually constructing a ggplot2 object using the returned columns.

    library(ggeffects)
    library(splines)
    library(datawizard)
    data(efc, package = "ggeffects")
    efc <- to_factor(efc, c("c161sex", "e42dep"))
    fit <- lm(barthtot ~ c12hour + bs(neg_c_7) * c161sex + e42dep, data = efc)
    
    # Get predictions for one term
    predict_response(fit, terms = "c12hour")
    
    # Plot using the built-in method
    mydf <- predict_response(fit, terms = "c12hour")
    plot(mydf)
    
    # Or manually with ggplot2
    library(ggplot2)
    ggplot(mydf, aes(x, predicted)) +
      geom_line() +
      geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.1)
  10. Calculate marginal effects with ggpredict()

    master

    The primary function for calculating marginal effects is ggpredict(). It requires a fitted model object and a terms argument. The terms argument can specify between one and three predictors.

    • If one term is provided, ggpredict() calculates predicted values of the response along the values of that term.
    • If multiple terms are provided, the first term is used for the x-axis, and subsequent terms are used for grouping (e.g., via different colors or facets).

    ggpredict() returns a tidy data frame with a consistent structure, making it compatible with ggplot2.

    library(ggeffects)
    # fit is a fitted model object (e.g., from lm, glm, etc.)
    # terms can be a single string or a vector of strings
    ggpredict(fit, terms = "c12hour")
    
    # For multiple terms (e.g., interaction/grouping)
    ggpredict(fit, terms = c("c172code", "c161sex"))
  11. Supported regression models in ggeffects

    master

    The ggeffects package supports a wide range of regression model objects. While predict_response() supports most of them, compatibility may vary depending on the marginalization method used (the margin argument). Some models might only be compatible with specific downstream functions like ggpredict(), ggemmeans(), ggeffect(), or ggaverage().

    Supported models include (but are not limited to):

    • Linear models: lm, lm_robust, rlm, ols
    • Generalized Linear Models: glm, glm.nb, vgam, vglm, gam, mgcv types
    • Mixed Models: lmerMod, glmerMod, merMod, brmsfit, glmmTMB, MCMCglmm
    • Robust/Quantile Regression: lmrob, rq, rqs, rqss
    • Survival/Cox models: coxph, survreg
    • And many others such as brms, fixest, glmmPQL, ordinal_weightit, etc.
    averaging, bamlss, bayesglm, bayesx, betabin, betareg, bglmer, bigglm, biglm, blmer, bracl, brglm, brmsfit, brmultinom, cgam, cgamm, clm, clm2, clmm, coxph, feglm, fixest, flac, flic, gam, Gam, gamlss, gamm, gamm4, gee, geeglm, glimML, glm, glm.nb, glm_weightit, glmer.nb, glmerMod, glmgee, glmmPQL, glmmTMB, glmrob, glmRob, glmmx, gls, hurdle, ivreg, lm, lm_robust, lme, lmerMod, lmrob, lmRob, logistf, logitr, lrm, mblogit, mclogit, MCMCglmm, merMod, merModLmerTest, MixMod, mixor, mlogit, multinom, multinom_weightit, negbin, nestedLogit, nlmerMod, ols, ordinal_weightit, orm, phyloglm, phylolm, plm, polr, rlm, rlmerMod, rq, rqs, rqss, sdmTMB, speedglm, speedlm, stanreg, survreg, svyglm, svyglm.nb, tidymodels, tobit, truncreg, vgam, vglm, wblm, wbm, Zelig-relogit, zeroinfl, zerotrunc
  12. Calculate adjusted predictions with predict_response()

    master

    The predict_response() function is the primary entry point for calculating adjusted predictions. It requires a model object and a terms argument specifying the 'focal terms' (the predictors you are interested in).

    Key details:

    • Response Scale: Predictions are always returned on the response scale, which is the most intuitive scale for interpretation.
    • Focal Terms: You can specify between 1 and 4 terms. The first term is used for the x-axis, and subsequent terms are used for grouping or faceting.
    • Marginalization: The margin argument determines how non-focal predictors (those not in terms) are handled.
    # Basic usage with one focal term
    predict_response(fit, terms = "c12hour")
    
    # Usage with multiple focal terms (for grouping/faceting)
    predict_response(fit, terms = c("neg_c_7", "c161sex", "e42dep"))