### Install modelbased Package (CRAN Release) Source: https://github.com/easystats/modelbased/blob/main/README.md Installs the latest stable release of the modelbased package from CRAN. This is the recommended installation method for most users. ```r install.packages("modelbased") ``` -------------------------------- ### Install Latest easystats Packages Source: https://github.com/easystats/modelbased/blob/main/README.md Updates all installed easystats packages to their latest available versions. This ensures you are using the most recent features and bug fixes. ```r easystats::install_latest() ``` -------------------------------- ### Estimate Contrasts for a Single Factor (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts.md This example shows how to estimate contrasts for a single factor ('am') in a model using the 'marginaleffects' backend. The output is formatted for readability, and it highlights the predicted variable and contrasted predictors. The function requires a model object and a contrast definition. ```r print(estimate_contrasts(model, contrast = "am", backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend and Marginal Effect Size Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md This example demonstrates estimating contrasts using the 'marginaleffects' backend with the 'marginal' effect size option. The output includes the standard marginal contrasts analysis along with an additional 'marginal_d' column representing the marginal effect size. ```R estimate_contrasts(model, effectsize = "marginal", backend = "marginaleffects") ``` -------------------------------- ### Estimate Contrasts with emmeans and Holm P-value Adjustment Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example illustrates using estimate_contrasts with the 'emmeans' backend and applying the 'Holm' method for p-value adjustment. The output includes the adjusted p-values, providing more conservative significance levels. ```r estimate_contrasts(model, backend = "emmeans", p_adjust = "holm") ``` -------------------------------- ### Estimate Contrasts with Interaction using marginaleffects Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example illustrates estimating contrasts for one variable ('c161sex') while conditioning on another ('c172code') using estimate_contrasts with the 'marginaleffects' backend. The output table displays contrasts for 'c161sex' within each level of 'c172code'. ```r print(estimate_contrasts(fit, "c161sex", "c172code", backend = "marginaleffects"), table_width = Inf, zap_small = TRUE) ``` -------------------------------- ### Install modelbased Package (Development Version) Source: https://github.com/easystats/modelbased/blob/main/README.md Installs the latest development version of the modelbased package from R-universe. This version may contain newer features but might be less stable than the CRAN release. ```r install.packages("modelbased", repos = "https://easystats.r-universe.dev") ``` -------------------------------- ### Estimate Contrasts for Multiple Variables (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example shows how to estimate contrasts for multiple variables ('time', 'coffee') simultaneously. The output is formatted to suppress small values and ensure table width is infinite for readability. It highlights interactions between the specified predictors. ```r print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with marginaleffects and Holm P-value Adjustment Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet shows how to use estimate_contrasts with the 'marginaleffects' backend and the 'Holm' p-value adjustment method. The results are presented with adjusted p-values, similar to the 'emmeans' example with the same adjustment. ```r estimate_contrasts(model, backend = "marginaleffects", p_adjust = "holm") ``` -------------------------------- ### Estimate Marginal Means with String Predictors (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/print.md This example shows how to use `estimate_means` with predictors specified as strings, defining the levels for contrast. It produces a table of estimated marginal means, similar to the list format, showing the predicted values for different combinations of predictor levels. ```r print(estimate_means(fit, c("c172code = c('low', 'high')", "c161sex = c('Female', 'Male')"), backend = "marginaleffects"), table_width = Inf, zap_small = TRUE) ``` -------------------------------- ### Estimate Contrasts Grouped by a Variable in R Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example demonstrates estimating contrasts for 'Species' while grouping the analysis by 'Petal.Width'. The `by` argument is used to specify the grouping variable, and `length = 4` suggests the number of levels or contrasts to consider. The output table includes the 'Petal.Width' in its columns, indicating the contrasts are calculated within each level of 'Petal.Width'. ```r print(estimate_contrasts(model, by = "Petal.Width", length = 4), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts for Multiple Variables in R Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example shows how to estimate contrasts for interactions between two variables ('Species' and 'Petal.Width'). The estimate_contrasts function is used with a vector specifying the contrast variables and a length parameter. The output table details the marginal contrasts for combinations of levels from both variables. ```r print(estimate_contrasts(model, contrast = c("Species", "Petal.Width"), length = 2), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts for Interaction Terms (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This example demonstrates estimating contrasts for interaction terms between two variables ('mined', 'spp'). It calculates the differences in predicted values when both variables change levels, showing the estimated effect of the interaction. ```r print(estimate_contrasts(model, contrast = c("mined", "spp"), backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate and Print Marginal Means with Continuous and Categorical Predictors (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md This example demonstrates estimating marginal means when predictors include both continuous and categorical variables. It uses `estimate_means` with the 'marginaleffects' backend, specifying a continuous variable ('barthtot') with a specific value (sd) and other categorical variables. The output table includes estimated means, standard errors, confidence intervals, and t-values for the specified predictor combinations. ```r print(estimate_means(fit, c("c12hour", "barthtot = [sd]", "c161sex", "c172code", "e16sex"), backend = "marginaleffects", length = 3), table_width = Inf) ``` -------------------------------- ### Summarize Slopes with Johnson-Neymann Intervals (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/summary_estimate_slopes.md This snippet demonstrates how to use the `summary()` function on an object named `slopes`, likely generated by `estimate_slopes()`. It displays Johnson-Neymann intervals, group-wise start and end points, direction of effect, and confidence levels. A message may appear if there's insufficient data for accurate interval determination. ```r summary(slopes) ``` -------------------------------- ### Estimate Contrasts by Age and Gender (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts_methods.md This R code snippet utilizes the `estimate_contrasts` function to perform model-based contrasts analysis. It focuses on the 'employed' predictor and stratifies the results by both 'age' and 'gender'. Similar to other examples, `zap_small = TRUE` and `table_width = Inf` are used for output formatting. ```r print(estimate_contrasts(estim, contrast = "employed", by = c("age", "gender")), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Configure Backend Selection and Global Options Source: https://context7.com/easystats/modelbased/llms.txt Explains how to configure default behaviors for the modelbased package, including selecting the estimation backend (emmeans vs. marginaleffects) and choosing the estimation approach (typical, average, population). ```r library(modelbased) # Set default backend globally options(modelbased_backend = "emmeans") # Use emmeans options(modelbased_backend = "marginaleffects") # Use marginaleffects (default) # Set default estimation approach options(modelbased_estimate = "typical") # Balanced grid (default) options(modelbased_estimate = "average") # Sample average options(modelbased_estimate = "population") # Counterfactual # Per-call backend selection model <- lm(Sepal.Width ~ Species, data = iris) estimate_means(model, by = "Species", backend = "emmeans") estimate_means(model, by = "Species", backend = "marginaleffects") # Plotting options options(modelbased_join_dots = FALSE) # Don't connect categorical points options(modelbased_numeric_as_discrete = 10) # Treat numerics with <=10 values as discrete options(modelbased_ribbon_alpha = 0.3) # Confidence band transparency # Integer handling for contrasts options(modelbased_integer = 5) # Treat integers with >5 unique values as continuous ``` -------------------------------- ### Fit Linear Model and Extract Parameters (R) Source: https://github.com/easystats/modelbased/blob/main/paper/paper.md This snippet demonstrates how to fit a linear model using the `lm()` function in R and then extract its parameters using the `parameters()` function from the `parameters` package. It shows a minimal output of the model coefficients, confidence intervals, and p-values. ```r library(easystats) model <- lm(Petal.Width ~ Petal.Length * Species, data = iris) parameters::parameters(model) |> print(select = "minimal") ``` -------------------------------- ### Estimate Contrasts: Joint Test with Select Printing (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/joint_test.md The `estimate_contrasts` function performs joint tests for specified contrasts within a statistical model. It allows for selection of printing options, as demonstrated by the example which tests 'time' contrasts across 'coffee' groups and a 'control' group. The output includes F-statistics and p-values, which are uncorrected in this example. ```r estimate_contrasts(m, contrast = "time", by = "coffee", comparison = "joint") ``` -------------------------------- ### Estimate Contrasts with emmeans Backend and Bootstrapped Effect Size Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md This code snippet demonstrates estimating contrasts using the 'emmeans' backend and bootstrapped effect size ('boot', 'hedges.g'). It shows the function call and the resulting marginal contrasts analysis output, including differences, confidence intervals, SE, t-values, p-values, and robust Cohen's d. ```R estimate_contrasts(model, effectsize = "boot", es_type = "hedges.g", backend = "emmeans") ``` -------------------------------- ### Setting modelbased Backend Option Source: https://github.com/easystats/modelbased/blob/main/README.md Demonstrates how to set the global option to specify which backend package (emmeans or marginaleffects) modelbased should use for calculations. This allows users to choose their preferred analytical approach. ```r options(modelbased_backend = "emmeans") options(modelbased_backend = "marginaleffects") ``` -------------------------------- ### Visualize Random Intercepts in Mixed-Effects Models (R) Source: https://github.com/easystats/modelbased/blob/main/README.md Generates and visualizes predictions from a linear mixed-effects model where only the intercept varies by subject. This helps in understanding individual starting points while keeping the slope constant across subjects. Requires the `lme4` and `modelbased` packages. ```r library(lme4) model <- lmer(Reaction ~ Days + (1 | Subject), data = sleepstudy) preds <- estimate_relation(model, include_random = TRUE) plot(preds, ribbon = list(alpha = 0)) ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (Default Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md This snippet illustrates estimating contrasts with the 'marginaleffects' backend. When no specific effect size is requested, it defaults to calculating the difference and associated statistics. The output includes marginal contrasts analysis with differences, SE, confidence intervals, t-values, and p-values. ```R estimate_contrasts(model, backend = "marginaleffects") ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (Parameter Equality) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet shows how to test the equality of two specific parameters (b5 and b3) using the 'marginaleffects' backend. The comparison is set to 'b5=b3'. The output provides the difference between these parameters, its standard error, confidence interval, t-value, and p-value, indicating whether the equality holds. The parameters involved are clearly defined. ```r print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects", p_adjust = "none", comparison = "b5=b3"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (No Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md This code shows how to estimate contrasts using the 'marginaleffects' backend while explicitly disabling effect size calculation by setting `effectsize = "none"`. The output focuses solely on the marginal contrasts analysis, providing differences, SE, confidence intervals, t-values, and p-values. ```R estimate_contrasts(model, effectsize = "none", backend = "marginaleffects") ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (Ratio) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet illustrates estimating marginal contrasts as ratios between levels of 'time', conditional on 'coffee'. It uses the 'marginaleffects' backend and specifies a ratio comparison. The output table displays the ratio of predicted values, along with standard errors, confidence intervals, t-values, and p-values. The analysis details the predicted variable, contrasted predictors, and averaged predictors. ```r print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects", p_adjust = "none", comparison = ratio ~ reference | coffee), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Marginal Means with Easystats Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md This R code snippet uses the 'easystats' package to estimate marginal means from a fitted statistical model. It specifies the predictor variables and the backend for calculation, outputting the results in a table format. Ensure the 'marginaleffects' package is installed and the 'fit' object is a valid statistical model. ```r print(estimate_means(fit, c("c161sex", "c172code", "e16sex", "nur_pst", "negc7d"), backend = "marginaleffects"), table_width = Inf) ``` -------------------------------- ### Load easystats Ecosystem Source: https://github.com/easystats/modelbased/blob/main/README.md Loads the entire easystats ecosystem, including modelbased and other related packages. This provides access to a broader set of statistical tools. ```r library("easystats") ``` -------------------------------- ### Estimate Contrasts and Standardized Effects Source: https://context7.com/easystats/modelbased/llms.txt Demonstrates how to estimate contrasts and standardize effect sizes from a statistical model. It covers simple contrasts, equivalence testing with ROPE, and contrasts for numeric predictors. ```r library(modelbased) # Standardized effect sizes contrasts_std <- estimate_contrasts(model, contrast = "Species") standardize(contrasts_std) # Equivalence testing with ROPE estimate_contrasts(model, contrast = "Species", equivalence = c(-0.5, 0.5)) # Contrasts of numeric predictor values model_num <- lm(Sepal.Width ~ Petal.Length, data = iris) estimate_contrasts(model_num, contrast = "Petal.Length = c(1, 3, 5)") ``` -------------------------------- ### Describe Smooth Term by Linear Parts in R Source: https://github.com/easystats/modelbased/blob/main/README.md Describes non-linear relationships (polynomials, splines, GAMs) in terms of their increasing and decreasing linear parts. The `describe_nonlinear` function is applied to predicted relationships. It requires the `modelbased` library and returns a table summarizing the start, end, length, change, slope, and R2 for each linear segment of the curve. ```r model <- lm(Sepal.Width ~ poly(Petal.Length, 2), data = iris) # 1. Visualize vizdata <- estimate_relation(model, length = 30) ggplot(vizdata, aes(x = Petal.Length, y = Predicted)) + geom_ribbon(aes(ymin = CI_low, ymax = CI_high), alpha = 0.3) + geom_line() + # Add original data points geom_point(data = iris, aes(x = Petal.Length, y = Sepal.Width)) + # Aesthetics theme_modern() ``` ```r # 2. Describe smooth line describe_nonlinear(vizdata, x = "Petal.Length") ``` -------------------------------- ### Estimate Contrasts with emmeans Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis using the emmeans backend. If no variable is specified for contrast estimation, it defaults to 'Species'. The output includes differences, confidence intervals, SE, t-values, and p-values. ```r estimate_contrasts(model, backend = "emmeans") ``` -------------------------------- ### Load modelbased Package Source: https://github.com/easystats/modelbased/blob/main/README.md Loads the modelbased package into the current R session, making its functions available for use. It is recommended to use library(easystats) to access the entire easystats ecosystem. ```r library("modelbased") ``` -------------------------------- ### Pool Predictions and Contrasts with Multiple Imputation Source: https://context7.com/easystats/modelbased/llms.txt Explains and demonstrates how to use `pool_predictions()` and `pool_contrasts()` to combine results from multiple imputed datasets using Rubin's rules. This is crucial for accurate inference when dealing with missing data. ```r library(modelbased) library(mice) # Create multiple imputations data("nhanes2", package = "mice") imp <- mice(nhanes2, m = 5, printFlag = FALSE) # Pool marginal means across imputations predictions_list <- lapply(1:5, function(i) { m <- lm(bmi ~ age + hyp + chl, data = complete(imp, action = i)) estimate_means(m, by = "age") }) pooled_means <- pool_predictions(predictions_list) print(pooled_means) # Pool contrasts across imputations contrasts_list <- lapply(1:5, function(i) { m <- lm(bmi ~ age + hyp + chl, data = complete(imp, action = i)) estimate_contrasts(m, contrast = "age") }) pooled_contrasts <- pool_contrasts(contrasts_list) print(pooled_contrasts) # Pool slopes (marginal effects) slopes_list <- lapply(1:5, function(i) { m <- lm(bmi ~ age + hyp + chl, data = complete(imp, action = i)) estimate_slopes(m, trend = "chl") }) pooled_slopes <- pool_slopes(slopes_list) print(pooled_slopes) ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (Specific Equality) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This code demonstrates testing a specific equality constraint between contrasts using the 'marginaleffects' backend. The comparison is defined as '(b2-b1)=(b4-b3)', testing if the difference between two pairs of parameters is equal. The output shows the calculated difference, standard error, confidence interval, t-value, and p-value for this specific hypothesis. It also lists the parameters involved in the comparison. ```r print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects", p_adjust = "none", comparison = "(b2-b1)=(b4-b3)"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with emmeans Backend (Marginal Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis with the emmeans backend, calculating marginal effect sizes. The output includes the contrast differences, confidence intervals, and the marginal effect size (e.g., marginal_d). ```r estimate_contrasts(model, effectsize = "marginal", backend = "emmeans") ``` -------------------------------- ### Estimate Contrasts with Marginaleffects Backend (Difference) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This code snippet demonstrates how to estimate marginal contrasts between different levels of 'time' and 'coffee' using the 'marginaleffects' backend. It calculates the difference between specified levels and presents the results with standard errors, confidence intervals, t-values, and p-values. The output table shows pairwise differences, and the analysis specifies the predicted variable and contrasted/averaged predictors. ```r print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects", p_adjust = "none"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Automated Plotting with visualisation_recipe() and plot() Source: https://context7.com/easystats/modelbased/llms.txt Creates publication-ready visualizations for modelbased objects using ggplot2. The `visualisation_recipe` function automatically maps predictors to appropriate aesthetics, and the `plot` function generates the visualization. These functions are useful for quickly exploring model relationships and can be customized by manipulating the recipe. ```r library(modelbased) library(ggplot2) library(see) # Basic relationship plot model <- lm(mpg ~ wt, data = mtcars) x <- estimate_relation(model) # Simple plot plot(x) # Get the visualization recipe for customization layers <- visualisation_recipe(x) print(layers) plot(layers) ``` -------------------------------- ### Estimate Contrasts with emmeans Backend (emmeans Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis using the emmeans backend, calculating effect sizes using the 'emmeans' method. This output includes both the contrast differences and the calculated effect sizes with their confidence intervals. ```r estimate_contrasts(model, effectsize = "emmeans", backend = "emmeans") ``` -------------------------------- ### Estimate Contrasts with Duplicated Levels (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts.md This code snippet demonstrates how to estimate contrasts for a model with duplicated levels using the 'marginaleffects' backend. It prints the results with specified formatting for clarity. The function takes a model object and a contrast definition as input. ```r print(estimate_contrasts(model, contrast = c("three", "vs", "am"), backend = "marginaleffects"), digits = 1, zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with emmeans Backend (No Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis with the emmeans backend, explicitly disabling effect size calculation. Similar to the default, it defaults to 'Species' for contrasts if not specified. The output focuses on the contrast differences and associated statistics. ```r estimate_contrasts(model, effectsize = "none", backend = "emmeans") ``` -------------------------------- ### Estimate Marginal Contrasts with modelbased in R Source: https://context7.com/easystats/modelbased/llms.txt Performs contrast analysis to estimate differences between factor levels or specific predictor values. Supports various comparison methods ('pairwise', 'reference', 'sequential', 'meandev', 'joint') and multiple comparison adjustments ('bonferroni', 'tukey'). ```r library(modelbased) # Basic pairwise contrasts between species model <- lm(Sepal.Width ~ Species, data = iris) contrasts <- estimate_contrasts(model, contrast = "Species") print(contrasts) # Contrasts with interaction - examine differences at specific values model_int <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) # Contrasts between species at different Petal.Length values estimate_contrasts( model_int, contrast = "Species", by = "Petal.Length", length = 3 ) # Different comparison methods estimate_contrasts(model, contrast = "Species", comparison = "reference") # vs first level estimate_contrasts(model, contrast = "Species", comparison = "sequential") # consecutive estimate_contrasts(model, contrast = "Species", comparison = "meandev") # vs grand mean # Multiple comparison adjustments estimate_contrasts(model, contrast = "Species", p_adjust = "bonferroni") estimate_contrasts(model, contrast = "Species", p_adjust = "tukey") # Joint hypothesis test for factorial designs estimate_contrasts(model, contrast = "Species", comparison = "joint") ``` -------------------------------- ### Summarize Derivative for marginaleffects Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md Summarizes the derivative calculated from the 'marginaleffects' backend of `estimate_slopes`. It presents Johnson-Neymann intervals and their significance. Similar to the 'emmeans' summary, it may warn about data limitations. ```r summary(deriv2) ``` -------------------------------- ### Estimate Contrasts with emmeans Backend (Bootstrapped Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis using the emmeans backend with bootstrapped effect sizes. This method provides Cohen's d values and their confidence intervals, calculated through bootstrapping. ```r estimate_contrasts(model, effectsize = "boot", backend = "emmeans") ``` -------------------------------- ### Estimate Marginal Contrasts Source: https://context7.com/easystats/modelbased/llms.txt Performs contrast analysis by estimating differences between each level of a factor or between specific predictor values. Supports various contrast methods including pairwise, sequential, reference, and polynomial contrasts. Results can be adjusted for multiple comparisons. ```APIDOC ## estimate_contrasts() - Estimate Marginal Contrasts ### Description Performs contrast analysis by estimating differences between each level of a factor or between specific predictor values. Supports various contrast methods including pairwise, sequential, reference, and polynomial contrasts. Results can be adjusted for multiple comparisons. ### Method POST ### Endpoint `/easystats/modelbased/estimate_contrasts` ### Parameters #### Query Parameters - **model** (object) - Required - The statistical model object (e.g., from lm(), glm()). - **contrast** (string) - Required - Specifies the factor or predictor for which to compute contrasts. - **by** (string or list) - Optional - Specifies the factor(s) or predictor(s) to condition on when computing contrasts. - **comparison** (string) - Optional - The type of comparison to perform ('pairwise', 'reference', 'sequential', 'meandev', 'joint'). Defaults to 'pairwise'. - **p_adjust** (string) - Optional - Method for adjusting p-values for multiple comparisons (e.g., 'bonferroni', 'tukey'). - **length** (integer) - Optional - The number of representative values to generate for continuous predictors when used with `by`. ### Request Body ```json { "model": "", "contrast": "Species", "by": "Petal.Length", "comparison": "reference", "p_adjust": "bonferroni", "length": 3 } ``` ### Response #### Success Response (200) - **data** (data.frame) - A data frame containing the estimated contrasts, standard errors, confidence intervals, t-statistics, and p-values. #### Response Example ```json { "data": [ { "Level1": "versicolor", "Level2": "setosa", "Difference": -0.66, "SE": 0.07, "CI_low": -0.79, "CI_high": -0.52, "t_stat": -9.69, "p_value": 0.0001 }, { "Level1": "virginica", "Level2": "setosa", "Difference": -0.45, "SE": 0.07, "CI_low": -0.59, "CI_high": -0.32, "t_stat": -6.68, "p_value": 0.0001 }, { "Level1": "virginica", "Level2": "versicolor", "Difference": 0.20, "SE": 0.07, "CI_low": 0.07, "CI_high": 0.34, "t_stat": 3.00, "p_value": 0.003 } ] } ``` ``` -------------------------------- ### Estimate Contrasts with emmeans Backend (Bootstrapped Robust Effect Size) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/estimate_contrasts_effectsize.md Performs marginal contrasts analysis using the emmeans backend with bootstrapped effect sizes, specifically using the 'akp.robust.d' type. This option provides robust bootstrapped effect size estimates. ```r estimate_contrasts(model, effectsize = "boot", es_type = "akp.robust.d", backend = "emmeans") ``` -------------------------------- ### Print Estimated Slopes with marginaleffects Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md Prints the estimated marginal effects for a specified trend variable using the 'marginaleffects' backend. This provides a similar output to the 'emmeans' backend, detailing the slope, its uncertainty, and statistical significance, along with the type of slope. ```r print(estimate_slopes(model, trend = "Petal.Length", backend = "marginaleffects")) ``` -------------------------------- ### Estimate Contrasts for Model Fit with Marginaleffects Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This code snippet demonstrates estimating a contrast for a fitted model ('fit') using the 'marginaleffects' backend. It tests the hypothesis that the difference between parameters b6 and b3 is equal to 0. The output includes the calculated difference, standard error, confidence interval, t-value, and p-value for this specific contrast. ```r estimate_contrasts(fit, c("e42dep", "c172code"), comparison = "b6-b3=0", backend = "marginaleffects") ``` -------------------------------- ### Visualize Model Relationships with estimate_relation Source: https://context7.com/easystats/modelbased/llms.txt Illustrates the use of `estimate_relation` for visualizing model relationships by generating expected values over a reference grid. It covers simple relationships, interactions, confidence levels, and integration with ggplot2. ```r library(modelbased) library(ggplot2) # Simple relationship model <- lm(mpg ~ wt, data = mtcars) relation <- estimate_relation(model) plot(relation) # Multiple confidence levels relation_multi <- estimate_relation(model, ci = c(0.5, 0.8, 0.95)) plot(relation_multi) # Interaction visualization model_int <- lm(Sepal.Width ~ Sepal.Length * Species, data = iris) relation_int <- estimate_relation(model_int, by = c("Sepal.Length", "Species")) plot(relation_int) # Control grid density estimate_relation(model, length = 100) # Custom visualization with ggplot2 ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color = Species), alpha = 0.5) + geom_ribbon(data = relation_int, aes(y = Predicted, ymin = CI_low, ymax = CI_high, fill = Species), alpha = 0.2) + geom_line(data = relation_int, aes(y = Predicted, color = Species), linewidth = 1) + theme_minimal() # Mixed models with random effects library(lme4) model_mixed <- lmer(Reaction ~ Days + (1 + Days | Subject), data = sleepstudy) # Population-level predictions (fixed effects only) estimate_relation(model_mixed) # Include random effects for each subject estimate_relation(model_mixed, include_random = TRUE) ``` -------------------------------- ### Estimate Pairwise Contrasts for Random Effects Levels (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts_methods.md This code snippet demonstrates how to use the estimate_contrasts function to compute pairwise comparisons between levels of random effects, specifically for 'gender', 'employed', and 'age'. The output is formatted for readability, suppressing small values and adjusting table width. ```r print(estimate_contrasts(estim, contrast = c("gender", "employed", "age")), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts by Age (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts_methods.md This R code snippet uses the `estimate_contrasts` function from the EasyStats library to calculate model-based contrasts. It compares 'gender' and 'employed' predictors, grouping the results by 'age'. The `zap_small = TRUE` argument removes small values, and `table_width = Inf` ensures the full table is displayed. ```r print(estimate_contrasts(estim, contrast = c("gender", "employed"), by = "age"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts for Multiple Variables using marginaleffects Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet shows how to estimate contrasts for multiple categorical variables ('c161sex', 'c172code') simultaneously using estimate_contrasts with the 'marginaleffects' backend. The output table provides detailed contrast analysis across combinations of these variables. ```r print(estimate_contrasts(fit, c("c161sex", "c172code"), backend = "marginaleffects"), table_width = Inf, zap_small = TRUE) ``` -------------------------------- ### Print Marginal Contrasts with Custom Formatting (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/print.md Prints marginal contrasts with custom formatting, allowing selection of specific output elements like the estimate and confidence interval, and indicating significance with stars. This provides a more visually interpretable summary of the contrasts. ```r print(out, select = "{estimate}{stars}|{ci}") ``` -------------------------------- ### Summarize Derivative for emmeans Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md Summarizes the derivative calculated from the 'emmeans' backend of `estimate_slopes`. It provides Johnson-Neymann intervals and indicates the direction and confidence of the effect. A message may appear if there is insufficient data to accurately determine intervals. ```r summary(deriv) ``` -------------------------------- ### Estimate Contrasts with Interaction - R Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts_methods.md This R code snippet demonstrates how to estimate contrasts for an interaction between 'age' and 'employed' predictors using the `estimate_contrasts` function. It utilizes the `estim` object and specifies the contrast and comparison arguments. The output is formatted for readability using `zap_small = TRUE` and `table_width = Inf`. ```r print(estimate_contrasts(estim, contrast = c("age", "employed"), comparison = "interaction"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts for Single Variable (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet demonstrates how to estimate simple contrasts for a single categorical variable ('Species') using the 'marginaleffects' backend. It prints the results in a formatted table, showing differences, standard errors, confidence intervals, and p-values. ```r print(estimate_contrasts(model, "Species", backend = "marginaleffects"), table_width = Inf) ``` -------------------------------- ### Customize Plot Aesthetics and Display Data/Predictions Source: https://context7.com/easystats/modelbased/llms.txt Demonstrates how to customize the aesthetics of plots generated by the modelbased package, including point color, line width, and ribbon transparency. It also shows how to display raw data alongside model predictions and create interaction plots with automatic color mapping. ```r plot(x, point = list(color = "red", alpha = 0.6, size = 3), line = list(color = "blue", linewidth = 2), ribbon = list(fill = "lightblue", alpha = 0.3) ) + theme_minimal() + labs(title = "MPG vs Weight", x = "Weight (1000 lbs)", y = "Miles per Gallon") # Show raw data with model predictions plot(x, show_data = TRUE) # Interaction plot with automatic color mapping model_int <- lm(Sepal.Width ~ Sepal.Length * Species, data = iris) plot(estimate_relation(model_int)) ``` -------------------------------- ### Estimate Contrasts with Marginal Effects (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This R code snippet uses the `marginaleffects` package to estimate contrasts between predictor levels. It specifies the model, the contrast to be estimated, and the variable to group by. The `zap_small` and `table_width` arguments are used for output formatting. The output shows the estimated differences, standard errors, confidence intervals, and p-values for each contrast. ```r print(estimate_contrasts(model, contrast = "mined", by = "spp", backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with 'by' Argument (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet illustrates estimating contrasts for a specific variable ('time') while grouping or 'by' another variable ('coffee'). This allows for examining how contrasts change across different levels of the 'by' variable. Small values are suppressed in the output. ```r print(estimate_contrasts(m, contrast = "time", by = "coffee", backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Slopes with marginaleffects Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md Estimates marginal effects using the 'marginaleffects' backend for a given model. The output is similar to the 'emmeans' backend, showing slopes, standard errors, confidence intervals, t-values, and p-values, along with the type of slope calculated. ```r estimate_slopes(model_lm, trend = "x", by = "x", backend = "marginaleffects") ``` -------------------------------- ### Create Visualization Matrix for Complex Interactions Source: https://github.com/easystats/modelbased/blob/main/README.md Generates a data grid to visualize complex interactions, particularly between two continuous variables. It allows for specifying values for predictors, including standardized changes (Z-scores), and then predicts model outcomes for this grid. The output can be further formatted and plotted using ggplot2. ```r # 1. Fit model and get visualization matrix model <- lm(Sepal.Length ~ Petal.Length * Petal.Width, data = iris) # 2. Create a visualisation matrix with expected Z-score values of Petal.Width vizdata <- insight::get_datagrid(model, by = c("Petal.Length", "Petal.Width = c(-1, 0, 1)")) # 3. Revert from expected SD to actual values vizdata <- unstandardize(vizdata, select = "Petal.Width") # 4. Add predicted relationship from the model vizdata <- modelbased::estimate_expectation(vizdata) # 5. Express Petal.Width as z-score ("-1 SD", "+2 SD", etc.) vizdata$Petal.Width <- effectsize::format_standardize(vizdata$Petal.Width, reference = iris$Petal.Width) ``` -------------------------------- ### Standardize and Unstandardize Model Estimates Source: https://context7.com/easystats/modelbased/llms.txt Details the `standardize()` and `unstandardize()` functions for converting model-based estimates to standardized units (z-scores). This facilitates comparison of effect sizes across different scales and studies. ```r library(modelbased) # Standardize predictions model <- lm(mpg ~ wt + hp, data = mtcars) preds <- estimate_relation(model) preds_std <- standardize(preds) print(preds_std) # Revert to original scale preds_original <- unstandardize(preds_std) # Standardize contrasts (effect sizes) model_factor <- lm(Sepal.Width ~ Species, data = iris) contrasts <- estimate_contrasts(model_factor, contrast = "Species") contrasts_std <- standardize(contrasts) # Cohen's d-like standardization print(contrasts_std) # Standardize only predictors, not response standardize(preds, include_response = FALSE) # Standardize slopes slopes <- estimate_slopes( lm(Sepal.Width ~ Species * Petal.Length, data = iris), trend = "Petal.Length", by = "Species" ) standardize(slopes) ``` -------------------------------- ### Estimate Marginal Means with Full Labels (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md This code snippet demonstrates how to use the estimate_means function to calculate and display estimated marginal means using the 'marginaleffects' backend. It specifies the model fit object and a vector of variables for which to estimate means. The output includes detailed labels for each category of the predictor variables. ```r print(estimate_means(fit, c("c161sex", "c172code", "e16sex", "nur_pst"), backend = "marginaleffects"), table_width = Inf) ``` -------------------------------- ### Visualize Relationship between Variables and Predictors (R) Source: https://github.com/easystats/modelbased/blob/main/paper/paper.md This code visualizes the relationship between the response variable (`Petal.Width`) and predictors (`Petal.Length`, `Species`) from a fitted linear model. It uses the `estimate_relation()` function from the `modelbased` package to calculate the relationship and then plots the results with data points shown. ```r estimate_relation(model, by = c("Petal.Length", "Species"), length = 100) |> plot(show_data = TRUE) ``` -------------------------------- ### Estimate Contrasts with Specific Variable Levels in R Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md This snippet illustrates how to perform contrasts by specifying particular levels for a variable. The 'Petal.Width' variable is contrasted at levels 1 and 2, in combination with 'Species'. The output table presents the marginal contrasts for these specific conditions. ```r print(estimate_contrasts(model, contrast = c("Species", "Petal.Width=c(1, 2)")), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Contrasts with Multiple Predictors in R Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts.md Estimates marginal contrasts for combinations of 'grp', 'time', and a specific level of 'x' ('a'). This demonstrates how to specify multiple predictors and interactions in `estimate_contrasts`. Output is optimized for display. ```r print(estimate_contrasts(model2, c("grp", "time", "x='a'")), zap_small = TRUE, table_width = Inf) ``` -------------------------------- ### Estimate Slopes (Marginal Effects) with modelbased Source: https://context7.com/easystats/modelbased/llms.txt Explains how to estimate marginal effects (slopes) of predictors using `estimate_slopes`. It covers interactions, Johnson-Neyman intervals, GAM models, and standardization. ```r library(modelbased) # Model with interaction model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) # Marginal effect of Petal.Length at each Species level slopes <- estimate_slopes(model, trend = "Petal.Length", by = "Species") print(slopes) # Slopes at specific values of another numeric predictor (Johnson-Neyman) model_jn <- lm(mpg ~ hp * wt, data = mtcars) slopes_jn <- estimate_slopes(model_jn, trend = "hp", by = "wt", length = 50) plot(slopes_jn) # Average marginal effect across all levels estimate_slopes( model, trend = "Petal.Length", by = "Species", comparison = ~I(mean(x)) ) # GAM models - derivatives of smooth terms library(mgcv) model_gam <- gam(Sepal.Width ~ s(Petal.Length), data = iris) slopes_gam <- estimate_slopes(model_gam, trend = "Petal.Length", by = "Petal.Length", length = 100) summary(slopes_gam) plot(slopes_gam) # Standardized slopes standardize(slopes) # Multiple comparison adjustment for Johnson-Neyman intervals estimate_slopes(model_jn, trend = "hp", by = "wt", p_adjust = "esarey") ``` -------------------------------- ### Control Plot Elements and Use Alternative Plotting Source: https://context7.com/easystats/modelbased/llms.txt Shows how to remove confidence bands from plots and demonstrates the use of `tinyplot` for base R graphics. This allows for fine-tuning plot appearance and leveraging different plotting systems. ```r # Remove confidence bands plot(x, ribbon = "none") # Use tinyplot for base R graphics library(tinyplot) tinyplot(x) ``` -------------------------------- ### Print Model-Based Predictions Including Grid (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/print.md Prints model-based predictions and includes the full prediction grid, which incorporates values of controlled predictors. This provides a more detailed view of the predictions across different combinations of predictor values. ```r print(estimate_relation(m, by = "qsec"), include_grid = TRUE) ``` -------------------------------- ### Estimate Marginal Contrasts by a Continuous Variable Source: https://github.com/easystats/modelbased/blob/main/README.md Estimates marginal contrasts at different values of a continuous variable (modulator). This is particularly useful when there's an interaction between a factor and a continuous variable, allowing you to see how contrasts change across the range of the continuous predictor. The output includes the modulator's value for each contrast. ```r model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) difference <- estimate_contrasts( model, contrast = "Species", by = "Petal.Length", length = 3 ) # no line break for table print(difference, table_width = Inf) ``` -------------------------------- ### Print Minimal Estimated Marginal Means (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/print.md Prints a simplified version of the estimated marginal means, showing only the mean and its confidence interval. This format is useful for a concise overview of the key predicted values. ```r print(out, select = "minimal") ``` -------------------------------- ### Estimate Pairwise Contrasts Between Categorical Levels (R) Source: https://github.com/easystats/modelbased/blob/main/paper/paper.md This code estimates all pairwise contrasts between the levels of a specified categorical predictor (`Species`) in a fitted model. It uses the `estimate_contrasts()` function from the `modelbased` package to compute the differences, standard errors, confidence intervals, t-statistics, and p-values. ```r estimate_contrasts(model, contrast = "Species") ``` -------------------------------- ### Generate Marginal Means and Slopes Plots Source: https://context7.com/easystats/modelbased/llms.txt Illustrates the creation of marginal means plots and slopes plots. Marginal means plots visualize estimated means for different groups, while slopes plots show the estimated relationship between a predictor and the response, optionally with a reference line. ```r # Marginal means plot means <- estimate_means(lm(Sepal.Width ~ Species, data = iris), by = "Species") plot(means) # Slopes plot with reference line model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) slopes <- estimate_slopes(model, trend = "Petal.Length", by = "Species") plot(slopes) + geom_hline(yintercept = 0, linetype = "dashed", color = "red") ``` -------------------------------- ### Overlay Fixed Effects on Individual Predictions (R) Source: https://github.com/easystats/modelbased/blob/main/README.md Plots individual random effects predictions and overlays the overall fixed effect prediction on the same graph. This comparison highlights how the average effect relates to individual variations. Requires `lme4` and `modelbased` packages. ```r fixed_pred <- estimate_relation(model) # This time, include_random is FALSE (default) plot(preds, ribbon = list(alpha = 0)) + # Previous plot geom_ribbon(data = fixed_pred, aes(x = Days, ymin = CI_low, ymax = CI_high), alpha = 0.4) + geom_line(data = fixed_pred, aes(x = Days, y = Predicted), linewidth = 2) ``` -------------------------------- ### Display Counterfactual Contrasts (G-computation) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/estimate_contrasts_counterfactual.md Prints the results of a Counterfactual Contrasts Analysis using G-computation. This output displays the differences, standard errors, confidence intervals, z-scores, and p-values for contrasts between treatment levels, averaging over specified predictors. ```r print(out, table_width = Inf) ``` -------------------------------- ### Estimate Marginal Means with Easystats (R) Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md This R code snippet demonstrates how to use the `estimate_means` function from the Easystats package to calculate and display estimated marginal means. It specifies the model fit object, predictor variables, and backend for calculation, along with options for output formatting. Dependencies include the Easystats package and a fitted statistical model. ```r print(estimate_means(fit, c("c161sex", "c172code", "e16sex", "nur_pst", "negc7d"), backend = "marginaleffects"), full_labels = FALSE, table_width = Inf) ``` -------------------------------- ### Print Estimated Slopes with emmeans Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md Prints the estimated marginal effects for a specified trend variable using the 'emmeans' backend. The output includes the slope, standard error, confidence interval, t-value, and p-value, indicating the estimated effect of the trend variable. ```r print(estimate_slopes(model, trend = "Petal.Length", backend = "emmeans")) ``` -------------------------------- ### Estimate Marginal Means using marginaleffects Backend Source: https://github.com/easystats/modelbased/blob/main/tests/testthat/_snaps/windows/print.md The `estimate_means` function, when used with the `backend = "marginaleffects"` option, estimates the marginal means of a model. It provides detailed output including means, standard errors, confidence intervals, and t-statistics, grouped by specified variables. This is valuable for comparing average effects across different levels of predictors. ```r estimate_means(model, by = c("c160age=[fivenum]", "c161sex"), backend = "marginaleffects") ```