### Install ggeffects from r-universe Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Installation command for the development version hosted on r-universe. ```R install.packages("ggeffects", repos = "https://strengejacke.r-universe.dev") ``` -------------------------------- ### Install ggeffects from GitHub Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Installation command for the development version using the remotes package. ```R remotes::install_github("strengejacke/ggeffects") ``` -------------------------------- ### Install ggeffects from CRAN Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Standard installation command for the stable release of the package. ```R install.packages("ggeffects") ``` -------------------------------- ### Install latest development version Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Convenience function to install the latest development version from r-universe. ```R ggeffects::install_latest() ``` -------------------------------- ### Display Pairwise Comparisons from brglm Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/brglm.md Use this to print pairwise comparisons generated by ggpredict for brglm models. Contrasts are presented as probabilities in %-points. ```R print(comp) ``` -------------------------------- ### Subset ggeffects objects Source: https://github.com/strengejacke/ggeffects/blob/master/NEWS.md Demonstrates how to subset ggeffects objects using standard data frame indexing syntax. ```R gge <- ggpredict(model, "x1") gge[c(1:2)] ``` -------------------------------- ### Print Compact Table of Predicted Values Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Use `print()` with `collapse_table = TRUE` and `collapse_ci = TRUE` for a more compact display of predicted values and their confidence intervals. ```r print(result, collapse_table = TRUE, collapse_ci = TRUE) ``` -------------------------------- ### Retrieve package citation Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Displays citation information for the ggeffects package. ```r citation('ggeffects') ``` -------------------------------- ### Print pairwise comparison output Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions_ggeffects.md Displays the results of pairwise comparisons for model factors. ```R print(out1) ``` ```R print(out) ``` -------------------------------- ### Load Libraries and Data for Prediction Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Loads the ggeffects, splines, and datawizard libraries, along with the efc dataset. Converts specified columns to factors for model compatibility. ```r library(ggeffects) library(splines) library(datawizard) data(efc, package = "ggeffects") efc <- to_factor(efc, c("c161sex", "e42dep")) ``` -------------------------------- ### Pairwise Comparisons with Grouping by Sex Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions_emmeans.md This snippet shows how to perform pairwise comparisons while grouping the results by a categorical variable, such as 'sex', using the emmeans engine. This is useful for examining differences within subgroups. ```R print(test_predictions(m, c("time", "coffee"), by = "sex", engine = "emmeans")) ``` -------------------------------- ### Calculate interaction contrasts with test_predictions Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions_emmeans.md Computes interaction contrasts for a model using the emmeans engine. Requires a fitted model object and specified terms. ```R print(test_predictions(m, terms = c("x1", "x2", "x3"), engine = "emmeans", test = "interaction")) ``` -------------------------------- ### Generating Representative Values Source: https://context7.com/strengejacke/ggeffects/llms.txt Use pretty_range or bracket-notation shortcuts in predict_response to define specific values for continuous predictors. ```r library(ggeffects) data(efc, package = "ggeffects") # Pretty range for a numeric variable pretty_range(efc$c12hour) #> [1] 0 20 40 60 80 100 120 140 160 180 # Specify number of intervals pretty_range(1:1000, n = 5) pretty_range(1:1000, length = 10) # Using special terms shortcuts in predict_response fit <- lm(barthtot ~ c12hour + neg_c_7, data = efc) # Mean +/- 1 SD predict_response(fit, terms = "c12hour [meansd]") # Quartiles predict_response(fit, terms = "c12hour [quart2]") # All unique values predict_response(fit, terms = "c12hour [all]") # Min/Max predict_response(fit, terms = "c12hour [minmax]") # Sample of values (useful for random effects) predict_response(fit, terms = "c12hour [sample=10]") # Custom function transformation predict_response(fit, terms = "c12hour [exp]") ``` -------------------------------- ### Print Model Predictions with Default CI Format Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Prints model predictions with confidence intervals enclosed in parentheses. This is the default behavior for the `print()` function when applied to ggeffects objects. ```r print(pr, group_name = FALSE, collapse_ci = TRUE) ``` -------------------------------- ### Print Predicted Values for Factors Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Use this to print predicted values for factors from a model. The output shows predicted values and their confidence intervals for different levels of a factor. ```r print(out, group_name = FALSE) ``` -------------------------------- ### Print glmmTMB and orderedbeta predictions Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/glmmTMB.md Displays the predicted proportions and confidence intervals for the specified model objects. ```R print(out1) ``` ```R print(out2) ``` -------------------------------- ### Predicting from Zero-Inflated Models Source: https://context7.com/strengejacke/ggeffects/llms.txt Use the type argument to specify whether to predict the response or the zero-inflation probability in zero-inflated models. ```r library(glmmTMB) data(Salamanders, package = "glmmTMB") fit_zi <- glmmTMB(count ~ spp + mined + (1 | site), ziformula = ~mined, family = poisson, data = Salamanders) # Predictions conditioning on zero-inflation predict_response(fit_zi, terms = "spp", type = "zero_inflated") # Predicted zero-inflation probability predict_response(fit_zi, terms = "mined", type = "zi_prob") ``` -------------------------------- ### Print Predicted Probabilities with ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/clm2.md Displays predicted probabilities from a ggpredict object. This output is useful for understanding how model predictions vary across different levels of predictor variables. ```r print(p) ``` -------------------------------- ### Print Subsets of Predicted Values Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_subsets.md Use subsetting with `c()` to select and print specific rows of predicted values and their confidence intervals. This is useful for inspecting particular data points. ```r print(gge[c(1:2, 4:6)]) ``` -------------------------------- ### Pairwise Comparisons without Grouping Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions_emmeans.md Use this to generate pairwise comparisons for specified variables using the emmeans engine. Ensure the model 'm' is appropriately defined. ```R print(test_predictions(m, c("time", "coffee"), engine = "emmeans")) ``` -------------------------------- ### ggaverage with collapsed tables Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/polr.md Print the ggaverage output for a polr model with collapsed tables for a more compact view. This option is useful for summarizing predictions across multiple categories and predictors in a single table. ```r print(pr, collapse_tables = TRUE) ``` -------------------------------- ### Perform Pairwise Comparisons with test_predictions Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions-margin.md Calculates pairwise comparisons for specified model terms. Contrasts are presented as probabilities in percentage points. ```R print(test_predictions(m, c("parfam [green, lib]", "year [1980, 2020]"))) ``` ```R print(test_predictions(m, c("parfam [green, lib]", "year [1980, 2020]"), margin = "marginalmeans")) ``` ```R print(test_predictions(m, c("parfam [green, lib]", "year [1980]"))) ``` ```R print(test_predictions(m, c("parfam [green, lib]", "year [1980]"), margin = "marginalmeans")) ``` ```R print(test_predictions(m, c("parfam [green, lib]", "year"))) ``` ```R print(test_predictions(m, c("parfam [green, lib]", "year"), margin = "marginalmeans")) ``` -------------------------------- ### Print Model Predictions with Custom CI Brackets Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Prints model predictions with confidence intervals enclosed in square brackets. This is achieved by specifying the `ci_brackets` argument in the `print()` function. ```r print(pr, group_name = FALSE, collapse_ci = TRUE, ci_brackets = c("[", "]")) ``` -------------------------------- ### Collapse Tables in ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Collapses tables for cleaner output and limits the number of rows displayed. ```R print(ggpredict(m, c("Petal.Length", "Species")), collapse_tables = TRUE, n = 3) ``` -------------------------------- ### Print ggpredict output Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/list_terms.md Displays the predicted values for the model terms. ```R print(out) ``` -------------------------------- ### Plot predictions using the built-in plot method Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Generates a default visualization for the predicted response object. ```r mydf <- predict_response(fit, terms = "c12hour") plot(mydf) ``` -------------------------------- ### Configuring value labels and precision in ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_digits.md Toggle the display of factor labels and adjust numeric precision for categorical predictors. ```R print(ggpredict(fit, "e42dep"), value_labels = FALSE) ``` ```R print(ggpredict(fit, "e42dep"), value_labels = TRUE) ``` ```R print(ggpredict(fit, "e42dep"), value_labels = TRUE, digits = 4) ``` -------------------------------- ### Visualize Adjusted Predictions with ggplot2 Source: https://context7.com/strengejacke/ggeffects/llms.txt Use the plot() method to create publication-ready ggplot2 figures from ggeffects objects. Supports customization of confidence bands, facets, color palettes, and raw data points. Can also show partial residuals and use log scales for the y-axis. ```r library(ggeffects) library(ggplot2) data(efc, package = "ggeffects") efc$c172code <- as.factor(efc$c172code) fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Basic plot mydf <- predict_response(fit, terms = "c12hour") plot(mydf) ``` ```r # Plot with raw data points plot(mydf, show_data = TRUE) ``` ```r # Customize appearance plot(mydf, colors = "metro", # Use metro color palette show_ci = TRUE, # Show confidence intervals ci_style = "ribbon", # Ribbon style for CI (or "errorbar", "dash", "dot") line_size = 1.2, dot_size = 3) ``` ```r # Multi-group predictions mydf2 <- predict_response(fit, terms = c("c12hour", "c172code")) plot(mydf2) ``` ```r # Faceted plot plot(mydf2, facets = TRUE) ``` ```r # Three-way interaction with automatic faceting mydf3 <- predict_response(fit, terms = c("c12hour", "c172code", "c161sex")) plot(mydf3) ``` ```r # Black and white plot plot(mydf2, colors = "bw") ``` ```r # Greyscale plot plot(mydf2, colors = "gs") ``` ```r # Add partial residuals for model diagnostics plot(mydf, show_residuals = TRUE, show_residuals_line = TRUE) ``` ```r # Log scale for y-axis (useful for binomial models) plot(mydf, log_y = TRUE) ``` ```r # Show available color palettes show_palettes() ``` -------------------------------- ### Print hypothesis test results Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_test_predictions.md Displays the hypothesis test object. Use this to view pairwise comparisons and statistical metrics. ```R print(ht) ``` ```R print(ht, table_width = Inf) ``` ```R print(ht) ``` -------------------------------- ### Print Hypothesis Test with Collapsed CI Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_test_predictions.md Prints hypothesis test results with collapsed confidence intervals. This format can simplify the presentation of pairwise comparison results. ```R print(out) ``` ```R print(out, collapse_ci = TRUE) ``` -------------------------------- ### Print ggpredict output Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/avg_predictions.md Displays the average predicted values for a model with specific conditions. ```R print(out1) ``` -------------------------------- ### Print Predicted Values with Custom Formatting Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Displays predicted values with group names enabled and confidence intervals collapsed into a single column using custom brackets. ```R print(pr, group_name = TRUE, collapse_ci = TRUE, ci_brackets = c("[", "]")) ``` -------------------------------- ### Print Test Predictions with Conditioned Values Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions-mixed.md Use test_predictions to generate pairwise comparisons for specified terms in a mixed model. The output displays contrasts, confidence intervals, and p-values. Contrasts are presented as counts. ```r print(test_predictions(fit, terms = c("e16sex", "c172code"))) ``` -------------------------------- ### Test Predictions for 3-way Interaction using Emmeans Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/test_predictions_emmeans.md Use this function to perform pairwise comparisons for a 3-way interaction when the emmeans engine is specified. Ensure the model 'm' and terms are correctly defined. ```R print(test_predictions(m, terms = c("x1", "x2", "x3"), engine = "emmeans")) ``` -------------------------------- ### Print Predicted Values with ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Displays predicted values for specified terms in a statistical model. By default, not all rows are shown. Use `n = Inf` to display all rows. ```R print(ggpredict(fit, terms = c("c12hour", "neg_c_7", "c161sex"))) ``` ```R print(ggpredict(fit, terms = c("c12hour", "neg_c_7", "c161sex")), n = Inf) ``` -------------------------------- ### Generate Predictions with glmmTMB Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_test_predictions.md Generates predictions from a glmmTMB model for a specific factor ('gear'). The output includes pairwise comparisons, confidence intervals, and p-values, presented as proportions. ```R print(test_predictions(m, "gear")) ``` -------------------------------- ### Visualize predictions with ggplot2 Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Uses the output of predict_response to create a line plot with confidence ribbons. ```r library(ggplot2) mydf <- predict_response(fit, terms = "c12hour") ggplot(mydf, aes(x, predicted)) + geom_line() + geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.1) ``` -------------------------------- ### Extracting Plot Labels and Data Source: https://context7.com/strengejacke/ggeffects/llms.txt Helper functions allow extraction of titles and labels from ggeffects objects for custom ggplot2 visualizations. ```r library(ggeffects) library(ggplot2) data(efc, package = "ggeffects") efc$c172code <- as.factor(efc$c172code) fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) mydf <- predict_response(fit, terms = c("c12hour", "c161sex", "c172code")) # Extract titles and labels get_title(mydf) # Response variable name/label get_x_title(mydf) # X-axis title (first focal term) get_y_title(mydf) # Y-axis title (response) get_legend_title(mydf) # Legend title (grouping variable) get_x_labels(mydf) # X-axis labels (if categorical) # Custom ggplot with extracted labels ggplot(mydf, aes(x = x, y = predicted, colour = group)) + geom_line() + geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = 0.1) + facet_wrap(~facet) + labs( x = get_x_title(mydf), y = get_y_title(mydf), colour = get_legend_title(mydf), title = get_title(mydf) ) # Convert to data frame with original variable names as.data.frame(mydf, terms_to_colnames = TRUE) ``` -------------------------------- ### Generate Plot with ggplot2 Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Create a line plot of predicted values using ggplot2, with facets for different categories. Requires the `result` object and `aes` mappings for x, predicted values, color, and facets. ```r ggplot(result, aes(x = x, y = predicted, colour = group)) + geom_line() + facet_wrap(~facet) ``` -------------------------------- ### Format ggaverage output Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/polr.md Format the output of ggaverage for a polr model into a more readable table. This includes columns for the predictor ('Infl'), predicted probability, confidence interval, and response category groups. ```r format(pr) ``` -------------------------------- ### Compute Average Counterfactual Predictions Source: https://context7.com/strengejacke/ggeffects/llms.txt Use ggaverage to compute average counterfactual predictions by averaging over all observations. This is useful for generalization to populations. Supports GLM models for predictions on the response scale. ```r library(ggeffects) data(efc, package = "ggeffects") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Average predictions (counterfactual) ggaverage(fit, terms = "c12hour") ``` ```r # With specific values ggaverage(fit, terms = "c12hour [0, 50, 100, 150]") ``` ```r # Using weighted predictions ggaverage(fit, terms = "c172code", weights = "c12hour") ``` ```r # For GLM models - predictions on response scale fit_glm <- glm(tot_sc_e ~ c12hour + neg_c_7 + c161sex, data = efc, family = poisson()) ggaverage(fit_glm, terms = "c12hour") ``` -------------------------------- ### Test Pairwise Comparisons and Contrasts Source: https://context7.com/strengejacke/ggeffects/llms.txt Use test_predictions to test differences between adjusted predictions for statistical significance. Supports pairwise comparisons, contrasts, and marginal effects. P-values can be adjusted using methods like 'tukey' or 'bonferroni'. ```r library(ggeffects) data(efc, package = "ggeffects") efc$c172code <- as.factor(efc$c172code) efc$c161sex <- as.factor(efc$c161sex) levels(efc$c161sex) <- c("male", "female") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Pairwise comparisons for a factor test_predictions(fit, "c172code") ``` ```r # Test predictions from a ggeffects object pred <- predict_response(fit, "c172code") test_predictions(pred) ``` ```r # Test for slope/trend of continuous predictor test_predictions(fit, "c12hour") ``` ```r # Interaction contrasts fit2 <- lm(barthtot ~ c12hour + c161sex * c172code + neg_c_7, data = efc) test_predictions(fit2, c("c161sex", "c172code"), test = "pairwise") ``` ```r # Contrasts by groups test_predictions(fit2, "c172code", by = "c161sex") ``` ```r # Different test types test_predictions(fit2, c("c161sex", "c172code"), test = "interaction") test_predictions(fit2, "c172code", test = "consecutive") test_predictions(fit2, "c172code", test = "contrast") ``` ```r # P-value adjustment test_predictions(fit, "c172code", p_adjust = "tukey") test_predictions(fit, "c172code", p_adjust = "bonferroni") ``` -------------------------------- ### ggpredict with polr model Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/polr.md Use ggpredict to obtain predicted probabilities for each category of the response variable from a polr model. The output shows predicted probabilities for 'Sat' across different levels of 'Infl', adjusted for other variables. ```r print(pr) ``` -------------------------------- ### Fit Linear Model for Prediction Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Fits a linear model using lm() with interaction and spline terms. This model will be used to generate adjusted predictions. ```r fit <- lm(barthtot ~ c12hour + bs(neg_c_7) * c161sex + e42dep, data = efc) ``` -------------------------------- ### Calculate Interaction Terms Source: https://context7.com/strengejacke/ggeffects/llms.txt Use ggemmeans to calculate interaction terms for specified variables in a model. ```r ggemmeans(fit, terms = c("c172code", "c161sex")) ``` -------------------------------- ### Print Weighted Average Predictions Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Calculates and prints average predicted values with collapsed tables for complex models. ```R print(ggaverage(m, c("Infl", "Type", "Sat")), collapse_tables = TRUE) ``` -------------------------------- ### ggpredict - Predictions with Non-focal Terms at Mean/Reference Source: https://context7.com/strengejacke/ggeffects/llms.txt `ggpredict()` computes predictions where non-focal predictors are held at their mean (numeric) or reference level (factors). This represents a "typical" observation approach and is called internally when `margin = "mean_reference"`. ```APIDOC ## ggpredict - Predictions with Non-focal Terms at Mean/Reference ### Description Computes predictions where non-focal predictors are held at their mean (numeric) or reference level (factors). This represents a "typical" observation approach and is called internally when `margin = "mean_reference"`. ### Method `ggpredict(model, terms, typical = c("numeric" = "mean", "factor" = "mode"), ...)` ### Parameters #### Path Parameters - **model** (model object) - Required - The statistical model object. - **terms** (character or list) - Required - The focal terms for which to compute predictions. Can be a single term, a vector of terms, or a list for interactions. - **typical** (character vector) - Optional - Specifies how non-focal predictors are handled. Defaults to "mean" for numeric and "mode" for factor variables. ### Request Example ```r library(ggeffects) data(efc, package = "ggeffects") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Basic usage - predictions for c12hour mydf <- ggpredict(fit, terms = "c12hour") print(mydf) # Predictions with grouping variable ggpredict(fit, terms = c("c12hour", "c172code")) # Specify typical values for covariates ggpredict(fit, terms = "c12hour", typical = c(numeric = "mean", factor = "mode")) # Range of values with step size ggpredict(fit, terms = "c12hour [0:100 by=10]") # Using named list format for terms ggpredict(fit, terms = list(c12hour = seq(0, 100, 20), c172code = c(1, 3))) # Three-way interaction ggpredict(fit, terms = c("c12hour", "c161sex", "c172code")) ``` ### Response #### Success Response (200) Returns a data frame with columns for the focal term(s), predicted values, and confidence intervals (e.g., `95% CI`). #### Response Example ``` # Predicted values of barthtot c12hour | Predicted | 95% CI ---------------------------------- 4 | 74.61 | 72.67, 76.55 12 | 74.05 | 72.18, 75.91 22 | 73.33 | 71.48, 75.19 ``` ``` -------------------------------- ### Use vector variables in terms within functions Source: https://github.com/strengejacke/ggeffects/blob/master/NEWS.md Shows how to pass a vector variable defined inside a function to the terms argument of ggpredict. ```R foo <- function(data) { fit <- lm(barthtot ~ c12hour + c172code, data = data) v <- c(20, 50, 70) ggpredict(fit, terms = "c12hour [v]") } foo(efc) ``` -------------------------------- ### Generate Plot with Base R Plot Function Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Use the base R `plot()` function to generate a plot from the `result` object. This provides a simpler plotting alternative to ggplot2. ```r plot(result) ``` -------------------------------- ### Adjust Confidence Interval Levels Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print.md Displays predicted values with different confidence interval levels. ```R print(out) ``` ```R print(out) ``` -------------------------------- ### Plot Marginal Effects with ggplot2 Source: https://github.com/strengejacke/ggeffects/blob/master/paper/paper.md Visualize the marginal effects calculated by ggpredict using ggplot2. This approach allows for customization of the plot. Requires the ggplot2 library. ```R 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) ``` -------------------------------- ### Handle Mixed Effects Models Source: https://context7.com/strengejacke/ggeffects/llms.txt ggeffects supports mixed-effects models from lme4, glmmTMB, and other packages. Provides options for population-level ('fixed') and unit-level ('random') predictions, prediction intervals, and empirical/counterfactual marginal predictions. ```r library(ggeffects) library(lme4) data(sleepstudy, package = "lme4") fit <- lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy) # Population-level predictions (default) predict_response(fit, terms = "Days", type = "fixed") ``` ```r # Unit-level predictions (include random effects) predict_response(fit, terms = c("Days", "Subject [sample=5]"), type = "random") ``` ```r # Prediction intervals (include residual variance) predict_response(fit, terms = "Days", interval = "prediction") ``` ```r # Using empirical/counterfactual approach for marginal predictions predict_response(fit, terms = "Days", margin = "empirical") ``` -------------------------------- ### ggemmeans - Estimated Marginal Means Source: https://context7.com/strengejacke/ggeffects/llms.txt `ggemmeans()` uses the emmeans package to compute estimated marginal means, where non-focal categorical predictors are marginalized over their levels. Called internally when `margin = "marginalmeans"`. ```APIDOC ## ggemmeans - Estimated Marginal Means ### Description Uses the emmeans package to compute estimated marginal means, where non-focal categorical predictors are marginalized over their levels. Called internally when `margin = "marginalmeans"`. ### Method `ggemmeans(model, terms, weights = "proportional", ...)` ### Parameters #### Path Parameters - **model** (model object) - Required - The statistical model object. - **terms** (character or list) - Required - The focal terms for which to compute estimated marginal means. - **weights** (character) - Optional - Specifies the weighting scheme for marginalization. Options include "proportional" (default), "equal", or a numeric vector. ### Request Example ```r library(ggeffects) data(efc, package = "ggeffects") efc$c172code <- as.factor(efc$c172code) fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Estimated marginal means ggemmeans(fit, terms = "c172code") # With different weighting options ggemmeans(fit, terms = "c172code", weights = "proportional") ggemmeans(fit, terms = "c172code", weights = "equal") ``` ### Response #### Success Response (200) Returns a data frame with columns for the focal term(s), estimated marginal means, and confidence intervals (e.g., `95% CI`). #### Response Example ``` # Predicted values of barthtot c172code | Predicted | 95% CI ----------------------------------- 1 | 69.07 | 66.68, 71.46 2 | 70.51 | 68.95, 72.07 3 | 67.88 | 65.17, 70.59 Adjusted for: * c12hour = 42.10 * neg_c_7 = 11.83 * c161sex = 1.00 ``` ``` -------------------------------- ### predict_response - Main Function for Computing Adjusted Predictions Source: https://context7.com/strengejacke/ggeffects/llms.txt The primary function `predict_response()` computes marginal means and adjusted predictions at the margin of specific values or levels from focal model terms. It acts as a unified wrapper around specialized functions (`ggpredict()`, `ggemmeans()`, `ggaverage()`) with the `margin` argument controlling how non-focal predictors are marginalized. ```APIDOC ## predict_response - Main Function for Computing Adjusted Predictions ### Description Computes marginal means and adjusted predictions at the margin of specific values or levels from focal model terms. It acts as a unified wrapper around specialized functions (`ggpredict()`, `ggemmeans()`, `ggaverage()`) with the `margin` argument controlling how non-focal predictors are marginalized. ### Method `predict_response(model, terms, margin = "mean_reference", ...)` ### Parameters #### Path Parameters - **model** (model object) - Required - The statistical model object. - **terms** (character or list) - Required - The focal terms for which to compute predictions. Can be a single term, a vector of terms, or a list for interactions. - **margin** (character) - Optional - Specifies how non-focal predictors are marginalized. Options include "mean_reference" (default), "marginalmeans", "empirical", "weighted.mean". ### Request Example ```r library(ggeffects) data(efc, package = "ggeffects") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Basic prediction for a single term predict_response(fit, terms = "c12hour") # Predictions with multiple focal terms (interactions) predict_response(fit, terms = c("c12hour", "c172code")) # Specify meaningful values using brackets predict_response(fit, terms = "c12hour [30:60]") # Use specific values for focal terms predict_response(fit, terms = c("c12hour", "c172code [1,3]")) # Hold non-focal terms at specific values with condition predict_response(fit, terms = "c12hour [40:60]", condition = c(neg_c_7 = 20)) # Different marginalization methods predict_response(fit, terms = "c12hour", margin = "mean_reference") predict_response(fit, terms = "c12hour", margin = "marginalmeans") predict_response(fit, terms = "c12hour", margin = "empirical") ``` ### Response #### Success Response (200) Returns a data frame with columns for the focal term(s), predicted values, and confidence intervals (e.g., `95% CI`). #### Response Example ``` # Predicted values of barthtot c12hour | Predicted | 95% CI ---------------------------------- 4 | 74.61 | 72.67, 76.55 12 | 74.05 | 72.18, 75.91 22 | 73.33 | 71.48, 75.19 36 | 72.33 | 70.43, 74.22 49 | 71.40 | 69.43, 73.37 70 | 69.90 | 67.78, 72.03 100 | 67.76 | 65.35, 70.16 168 | 62.91 | 59.57, 66.24 Adjusted for: * neg_c_7 = 11.83 * c161sex = 1 * c172code = 2 ``` ``` -------------------------------- ### Predictions with Non-focal Terms at Mean/Reference using ggpredict Source: https://context7.com/strengejacke/ggeffects/llms.txt ggpredict() computes predictions by holding non-focal predictors at their mean (numeric) or reference level (factors). This function is called internally by predict_response() when margin = "mean_reference". ```R library(ggeffects) data(efc, package = "ggeffects") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Basic usage - predictions for c12hour mydf <- ggpredict(fit, terms = "c12hour") mydf ``` ```R # Predictions with grouping variable ggpredict(fit, terms = c("c12hour", "c172code")) ``` ```R # Specify typical values for covariates ggpredict(fit, terms = "c12hour", typical = c(numeric = "mean", factor = "mode")) ``` ```R # Range of values with step size ggpredict(fit, terms = "c12hour [0:100 by=10]") ``` ```R # Using named list format for terms ggpredict(fit, terms = list(c12hour = seq(0, 100, 20), c172code = c(1, 3))) ``` ```R # Three-way interaction ggpredict(fit, terms = c("c12hour", "c161sex", "c172code")) ``` -------------------------------- ### Calculate and visualize predictions for multiple focal predictors Source: https://github.com/strengejacke/ggeffects/blob/master/README.rmd Handles up to four terms, allowing for grouping and faceting in the resulting plots. ```r result <- predict_response(fit, terms = c("neg_c_7", "c161sex", "e42dep")) # we want a more compact table, thus we use `print()` explicitly print(result, collapse_table = TRUE, collapse_ci = TRUE) ggplot(result, aes(x = x, y = predicted, colour = group)) + geom_line() + facet_wrap(~facet) ``` ```r plot(result) ``` -------------------------------- ### Calculate Marginal Effects with ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/paper/paper.md Use ggpredict to calculate predicted values for a linear model. Requires the ggeffects and sjlabelled libraries. The 'terms' argument specifies the variable for which to calculate effects. ```R library(ggeffects) library(sjlabelled) data(efc) efc$c172code <- as_factor(efc$c172code) fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) ggpredict(fit, terms = "c12hour") ``` -------------------------------- ### Plot Marginal Effects with plot() Method Source: https://github.com/strengejacke/ggeffects/blob/master/paper/paper.md Use the built-in plot() method for ggpredict objects to quickly generate a ggplot object representing the marginal effects. This method handles common plot characteristics. ```R p <- ggpredict(fit, terms = c("c172code", "c161sex")) plot(p) ``` -------------------------------- ### Test pairwise comparisons for glmmTMB Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/windows/print_zero_inflation.md Performs pairwise comparisons on the predicted counts from a zero-inflated model fitted with glmmTMB. Contrasts are presented as counts. ```r print(test_predictions(out)) ``` -------------------------------- ### Applying Robust Standard Errors Source: https://context7.com/strengejacke/ggeffects/llms.txt Specify the vcov argument to use robust standard errors or custom variance-covariance matrices for inference. ```r library(ggeffects) data(efc, package = "ggeffects") fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Heteroscedasticity-consistent standard errors predict_response(fit, terms = "c12hour", vcov = "HC3") # Various HC types predict_response(fit, terms = "c12hour", vcov = "HC0") predict_response(fit, terms = "c12hour", vcov = "HC1") predict_response(fit, terms = "c12hour", vcov = "HC4") # Cluster-robust standard errors (requires clubSandwich) # predict_response(fit, terms = "c12hour", vcov = "CR2", vcov_args = list(cluster = efc$cluster_var)) # Bootstrap standard errors predict_response(fit, terms = "c12hour", vcov = "BS") # Custom variance-covariance matrix my_vcov <- sandwich::vcovHC(fit, type = "HC3") predict_response(fit, terms = "c12hour", vcov = my_vcov) ``` -------------------------------- ### Compute Adjusted Predictions with predict_response Source: https://context7.com/strengejacke/ggeffects/llms.txt Use predict_response() to calculate marginal means and adjusted predictions. It supports various marginalization methods via the 'margin' argument and allows specifying focal terms and conditions. ```R library(ggeffects) data(efc, package = "ggeffects") # Fit a linear model fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Basic prediction for a single term predict_response(fit, terms = "c12hour") ``` ```R # Predictions with multiple focal terms (interactions) predict_response(fit, terms = c("c12hour", "c172code")) ``` ```R # Specify meaningful values using brackets predict_response(fit, terms = "c12hour [30:60]") ``` ```R # Use specific values for focal terms predict_response(fit, terms = c("c12hour", "c172code [1,3]")) ``` ```R # Hold non-focal terms at specific values with condition predict_response(fit, terms = "c12hour [40:60]", condition = c(neg_c_7 = 20)) ``` ```R # Different marginalization methods predict_response(fit, terms = "c12hour", margin = "mean_reference") # default predict_response(fit, terms = "c12hour", margin = "marginalmeans") # weighted average predict_response(fit, terms = "c12hour", margin = "empirical") # counterfactual ``` -------------------------------- ### Pooling Predictions from Imputed Data Source: https://context7.com/strengejacke/ggeffects/llms.txt Use pool_predictions to combine results from multiple imputed datasets generated by the mice package. ```r library(ggeffects) library(mice) # Create multiply imputed datasets data("nhanes2", package = "mice") imp <- mice(nhanes2, m = 5, printFlag = FALSE) # Generate predictions for each imputed dataset predictions <- lapply(1:5, function(i) { m <- lm(bmi ~ age + hyp + chl, data = complete(imp, action = i)) predict_response(m, "age") }) # Pool predictions pooled <- pool_predictions(predictions) pooled #> # Predicted values of bmi #> #> age | Predicted | 95% CI #> -------------------------------- #> 20-39 | 27.37 | 24.89, 29.85 #> 40-59 | 28.64 | 26.03, 31.26 #> 60-99 | 26.99 | 23.43, 30.54 # Plot pooled predictions plot(pooled) ``` -------------------------------- ### Adjusting digits and row display in ggpredict Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/print_digits.md Control the precision of numeric output and the number of rows displayed in the console. ```R print(ggpredict(m, "Petal.Length"), digits = 5) ``` ```R print(ggpredict(m, "Petal.Length"), digits = 4, n = 3) ``` -------------------------------- ### Predicted Probabilities with Covariate Adjustment Source: https://github.com/strengejacke/ggeffects/blob/master/tests/testthat/_snaps/clm.md This snippet generates predicted probabilities for an ordinal model, showing the effect of a covariate ('contact') across different levels of the outcome and predictor ('temp'). ```r print(p2) ``` -------------------------------- ### Compute Estimated Marginal Means with ggemmeans Source: https://context7.com/strengejacke/ggeffects/llms.txt ggemmeans() calculates estimated marginal means using the emmeans package. Non-focal categorical predictors are marginalized over their levels. This function is called internally by predict_response() when margin = "marginalmeans". ```R library(ggeffects) data(efc, package = "ggeffects") efc$c172code <- as.factor(efc$c172code) fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc) # Estimated marginal means ggemmeans(fit, terms = "c172code") ``` ```R # With different weighting options ggemmeans(fit, terms = "c172code", weights = "proportional") ggemmeans(fit, terms = "c172code", weights = "equal") ``` -------------------------------- ### Calculate Adjusted Predictions for One Predictor Source: https://github.com/strengejacke/ggeffects/blob/master/README.md Calculates adjusted predictions for the 'barthtot' response variable based on the 'c12hour' predictor. Predictions are adjusted for other model variables. ```r predict_response(fit, terms = "c12hour") ```