marginaleffects
Primary source of information: https://marginaleffects.com
Free book, case studies, and vignettes are available there.
Package manual for R and Python, plus a guide to the companion book.
Book: Model to Meaning: How to Interpret Statistical Models in R and Python
Core framework: Five questions for every analysis
Every interpretation task can be decomposed into five disciplined questions:
- Quantity: What estimand? (predictions, comparisons, slopes, or tests)
- Predictors (Grid): Where to evaluate? (observed values, counterfactual scenarios, balanced grids)
- Aggregation: Over whom? (unit-level, group means with
by=, weighted averages)
- Uncertainty: Which inference method? (delta method, robust SE, bootstrap, Bayesian)
- Test: What hypothesis? (null tests, equivalence, pairwise contrasts)
Quick start
Chapter summaries: Read chapters/<chapter>.qmd
Function reference: Read man/r/<function>.md or man/python/<function>.md
When to use this skill
- User asks about predictions, comparisons, slopes, or marginal effects
- User needs help choosing estimands (ATE, ATT, CATE, risk difference, odds ratio)
- User asks about marginaleffects function syntax or arguments
- User wants to interpret model results or test hypotheses
- User mentions counterfactual analysis, G-computation, or causal inference
- User references Model to Meaning chapters
Instructions
Classify the request:
- Conceptual: Which estimand? How to interpret? → Use
chapters/
- Implementation: Function syntax, arguments, code → Use
man/r/ or man/python/
- Mixed: Start with conceptual framing, then provide code
Read the relevant source files:
- Book chapters:
chapters/framework.qmd, chapters/predictions.qmd, chapters/comparisons.qmd, chapters/slopes.qmd, chapters/hypothesis.qmd, etc.
- R reference:
man/r/predictions.md, man/r/comparisons.md, man/r/slopes.md, man/r/hypotheses.md, man/r/datagrid.md
- Python reference:
man/python/predictions.md, man/python/comparisons.md, man/python/slopes.md, man/python/hypotheses.md
Apply the five-question framework to organize your response:
- Help user define the estimand (Quantity)
- Clarify where to evaluate it (Grid)
- Determine aggregation level (Aggregation)
- Recommend uncertainty quantification (Uncertainty)
- Specify hypothesis if testing (Test)
Provide concrete code examples using the correct function for their language (R or Python)
Available resources
Book chapters (chapters/)
| File |
Topic |
Chapter focus |
framework.qmd |
Five-question framework (start here) |
Defines the five questions and core quantities (predictions, comparisons, slopes) for turning models into intuitive estimands. |
predictions.qmd |
Predicted values and expected outcomes |
Defines predictions, grids, aggregation, and tests with predictions()/avg_predictions(). |
comparisons.qmd |
Counterfactual comparisons, ATE, ATT, risk ratios |
Defines counterfactual comparisons, effect functions, grids, and aggregation with comparisons()/avg_comparisons(). |
slopes.qmd |
Marginal effects, partial derivatives |
Defines slopes as partial derivatives, conditional on predictors; uses slopes()/avg_slopes(). |
hypothesis.qmd |
Hypothesis testing and equivalence |
Null vs equivalence tests for any quantity using hypothesis and equivalence arguments. |
interactions.qmd |
Interaction effects and effect modification |
Interprets heterogeneity and nonlinearity with interactions and polynomials using predictions, comparisons, and slopes. |
categorical.qmd |
Categorical predictors and contrasts |
Applies the framework to categorical/ordinal outcomes with predictions and comparisons by outcome level. |
experiments.qmd |
Experimental designs |
ATE in experiments and factorial designs via avg_comparisons() and robust SEs. |
gcomputation.qmd |
G-computation and causal inference |
G-computation steps for ATE/ATT/ATU/CATE with counterfactual prediction grids. |
uncertainty.qmd |
Inference methods (delta, bootstrap, Bayesian) |
Delta method, bootstrap, simulation, conformal prediction, and robust/clustered standard errors via inferences()/vcov. |
mrp.qmd |
Multilevel regression and poststratification |
Multilevel models and poststratification with predictions and comparisons in mixed effects. |
ml.qmd |
Machine learning models |
Model auditing with predictions, comparisons, and slopes for ML frameworks. |
challenge.qmd |
The interpretation challenge |
Defines analysis goals, estimands, and why coefficients need transformation. |
R function reference (man/r/)
Core functions (includes avg_* variants): predictions.md, comparisons.md, slopes.md, hypotheses.md
Grids: datagrid.md
Plots: plot_predictions.md, plot_comparisons.md, plot_slopes.md
Utilities: posterior_draws.md, inferences.md, get_dataset.md
Python function reference (man/python/)
Core: predictions.md, avg_predictions.md, comparisons.md, avg_comparisons.md, slopes.md, avg_slopes.md, hypotheses.md
Grids: datagrid.md
Plots: plot_predictions.md, plot_comparisons.md, plot_slopes.md
Model fitting: fit_statsmodels.md, fit_sklearn.md, fit_linearmodels.md
Examples
Logit model example
R:
library(marginaleffects)
# Fit logistic regression
mod <- glm(am ~ hp + wt, data = mtcars, family = binomial)
# Average marginal effects (slopes on probability scale)
avg_slopes(mod)
# Predicted probabilities at specific values
predictions(mod, newdata = datagrid(hp = c(100, 150, 200), wt = 3))
# Average treatment effect: compare hp = 150 vs hp = 100
avg_comparisons(mod, variables = list(hp = c(100, 150)))
# Risk ratio for a 50-unit increase in hp
avg_comparisons(mod, variables = list(hp = 50), comparison = "ratio")
Python:
import marginaleffects as me
import statsmodels.formula.api as smf
# Fit logistic regression
mod = smf.logit("am ~ hp + wt", data=me.get_dataset("mtcars")).fit()
# Average marginal effects
me.avg_slopes(mod)
# Predicted probabilities at specific values
me.predictions(mod, newdata=me.datagrid(mod, hp=[100, 150, 200], wt=3))
# Average treatment effect: compare hp = 150 vs hp = 100
me.avg_comparisons(mod, variables={"hp": [100, 150]})
User asks about choosing an estimand:
→ Read chapters/framework.qmd and chapters/comparisons.qmd, explain the five-question framework, recommend the appropriate quantity (e.g., avg_comparisons() for ATE).
User asks how to compute marginal effects:
→ Read man/r/slopes.md or man/python/slopes.md, provide syntax with relevant arguments.
User wants to test treatment effect heterogeneity:
→ Read chapters/comparisons.qmd for CATE concepts, then man/r/hypotheses.md for testing syntax with by= groups.
User asks about counterfactual grids:
→ Read chapters/framework.qmd (Predictors section) and man/r/datagrid.md for datagrid() usage.
Best practices
- Ask about language preference: If the user hasn't specified R or Python, ask which they prefer before providing code examples
- Always frame responses using the five-question framework when appropriate
- Cite specific sections from summaries or manuals
- Mention
get_dataset() when users need example data
- For mixed requests, start with conceptual framing then show implementation
1---2name: marginaleffects3description: Manual for the marginaleffects R and Python package, and guide to the book "Model to Meaning". Use when users ask about predictions, comparisons, slopes, marginal effects, average treatment effects (ATE/ATT/CATE), hypothesis testing, contrasts, counterfactuals, risk ratios, odds ratios, causal inference with G-computation, or need help with marginaleffects functions like predictions(), comparisons(), slopes(), hypotheses(), datagrid(), avg_predictions(), avg_comparisons(), avg_slopes(), or plot functions.4license: CC-BY-4.05metadata:6 source: https://skillmd.com/skills/brycewang-stanford/marginaleffects7 upstream: https://marginaleffects.com8 maintainer: vincentarelbundock9allowed-tools: Read, Grep, Glob10---1112# marginaleffects1314Primary source of information: https://marginaleffects.com15Free book, case studies, and vignettes are available there.1617Package manual for R and Python, plus a guide to the companion book.1819**Book**: *Model to Meaning: How to Interpret Statistical Models in R and Python*20- Author: Vincent Arel-Bundock (2026)21- Publisher: CRC Press22- Free online: https://marginaleffects.com (primary source with many case studies and vignettes)23- Print: https://routledge.com/97810329087242425## Core framework: Five questions for every analysis2627Every interpretation task can be decomposed into five disciplined questions:28291. **Quantity**: What estimand? (predictions, comparisons, slopes, or tests)302. **Predictors (Grid)**: Where to evaluate? (observed values, counterfactual scenarios, balanced grids)313. **Aggregation**: Over whom? (unit-level, group means with `by=`, weighted averages)324. **Uncertainty**: Which inference method? (delta method, robust SE, bootstrap, Bayesian)335. **Test**: What hypothesis? (null tests, equivalence, pairwise contrasts)3435## Quick start3637**Chapter summaries**: Read `chapters/<chapter>.qmd`38**Function reference**: Read `man/r/<function>.md` or `man/python/<function>.md`3940## When to use this skill4142- User asks about predictions, comparisons, slopes, or marginal effects43- User needs help choosing estimands (ATE, ATT, CATE, risk difference, odds ratio)44- User asks about marginaleffects function syntax or arguments45- User wants to interpret model results or test hypotheses46- User mentions counterfactual analysis, G-computation, or causal inference47- User references Model to Meaning chapters4849## Instructions50511. **Classify the request**:52 - Conceptual: Which estimand? How to interpret? → Use `chapters/`53 - Implementation: Function syntax, arguments, code → Use `man/r/` or `man/python/`54 - Mixed: Start with conceptual framing, then provide code55562. **Read the relevant source files**:57 - Book chapters: `chapters/framework.qmd`, `chapters/predictions.qmd`, `chapters/comparisons.qmd`, `chapters/slopes.qmd`, `chapters/hypothesis.qmd`, etc.58 - R reference: `man/r/predictions.md`, `man/r/comparisons.md`, `man/r/slopes.md`, `man/r/hypotheses.md`, `man/r/datagrid.md`59 - Python reference: `man/python/predictions.md`, `man/python/comparisons.md`, `man/python/slopes.md`, `man/python/hypotheses.md`60613. **Apply the five-question framework** to organize your response:62 - Help user define the estimand (Quantity)63 - Clarify where to evaluate it (Grid)64 - Determine aggregation level (Aggregation)65 - Recommend uncertainty quantification (Uncertainty)66 - Specify hypothesis if testing (Test)67684. **Provide concrete code examples** using the correct function for their language (R or Python)6970## Available resources7172### Book chapters (`chapters/`)73| File | Topic | Chapter focus |74|------|-------|---------------|75| `framework.qmd` | Five-question framework (start here) | Defines the five questions and core quantities (predictions, comparisons, slopes) for turning models into intuitive estimands. |76| `predictions.qmd` | Predicted values and expected outcomes | Defines predictions, grids, aggregation, and tests with `predictions()`/`avg_predictions()`. |77| `comparisons.qmd` | Counterfactual comparisons, ATE, ATT, risk ratios | Defines counterfactual comparisons, effect functions, grids, and aggregation with `comparisons()`/`avg_comparisons()`. |78| `slopes.qmd` | Marginal effects, partial derivatives | Defines slopes as partial derivatives, conditional on predictors; uses `slopes()`/`avg_slopes()`. |79| `hypothesis.qmd` | Hypothesis testing and equivalence | Null vs equivalence tests for any quantity using `hypothesis` and `equivalence` arguments. |80| `interactions.qmd` | Interaction effects and effect modification | Interprets heterogeneity and nonlinearity with interactions and polynomials using predictions, comparisons, and slopes. |81| `categorical.qmd` | Categorical predictors and contrasts | Applies the framework to categorical/ordinal outcomes with predictions and comparisons by outcome level. |82| `experiments.qmd` | Experimental designs | ATE in experiments and factorial designs via `avg_comparisons()` and robust SEs. |83| `gcomputation.qmd` | G-computation and causal inference | G-computation steps for ATE/ATT/ATU/CATE with counterfactual prediction grids. |84| `uncertainty.qmd` | Inference methods (delta, bootstrap, Bayesian) | Delta method, bootstrap, simulation, conformal prediction, and robust/clustered standard errors via `inferences()`/`vcov`. |85| `mrp.qmd` | Multilevel regression and poststratification | Multilevel models and poststratification with predictions and comparisons in mixed effects. |86| `ml.qmd` | Machine learning models | Model auditing with predictions, comparisons, and slopes for ML frameworks. |87| `challenge.qmd` | The interpretation challenge | Defines analysis goals, estimands, and why coefficients need transformation. |8889### R function reference (`man/r/`)90Core functions (includes `avg_*` variants): `predictions.md`, `comparisons.md`, `slopes.md`, `hypotheses.md`91Grids: `datagrid.md`92Plots: `plot_predictions.md`, `plot_comparisons.md`, `plot_slopes.md`93Utilities: `posterior_draws.md`, `inferences.md`, `get_dataset.md`9495### Python function reference (`man/python/`)96Core: `predictions.md`, `avg_predictions.md`, `comparisons.md`, `avg_comparisons.md`, `slopes.md`, `avg_slopes.md`, `hypotheses.md`97Grids: `datagrid.md`98Plots: `plot_predictions.md`, `plot_comparisons.md`, `plot_slopes.md`99Model fitting: `fit_statsmodels.md`, `fit_sklearn.md`, `fit_linearmodels.md`100101## Examples102103### Logit model example104105**R:**106```r107library(marginaleffects)108109# Fit logistic regression110mod <- glm(am ~ hp + wt, data = mtcars, family = binomial)111112# Average marginal effects (slopes on probability scale)113avg_slopes(mod)114115# Predicted probabilities at specific values116predictions(mod, newdata = datagrid(hp = c(100, 150, 200), wt = 3))117118# Average treatment effect: compare hp = 150 vs hp = 100119avg_comparisons(mod, variables = list(hp = c(100, 150)))120121# Risk ratio for a 50-unit increase in hp122avg_comparisons(mod, variables = list(hp = 50), comparison = "ratio")123```124125**Python:**126```python127import marginaleffects as me128import statsmodels.formula.api as smf129130# Fit logistic regression131mod = smf.logit("am ~ hp + wt", data=me.get_dataset("mtcars")).fit()132133# Average marginal effects134me.avg_slopes(mod)135136# Predicted probabilities at specific values137me.predictions(mod, newdata=me.datagrid(mod, hp=[100, 150, 200], wt=3))138139# Average treatment effect: compare hp = 150 vs hp = 100140me.avg_comparisons(mod, variables={"hp": [100, 150]})141```142143**User asks about choosing an estimand:**144→ Read `chapters/framework.qmd` and `chapters/comparisons.qmd`, explain the five-question framework, recommend the appropriate quantity (e.g., `avg_comparisons()` for ATE).145146**User asks how to compute marginal effects:**147→ Read `man/r/slopes.md` or `man/python/slopes.md`, provide syntax with relevant arguments.148149**User wants to test treatment effect heterogeneity:**150→ Read `chapters/comparisons.qmd` for CATE concepts, then `man/r/hypotheses.md` for testing syntax with `by=` groups.151152**User asks about counterfactual grids:**153→ Read `chapters/framework.qmd` (Predictors section) and `man/r/datagrid.md` for `datagrid()` usage.154155## Best practices156157- **Ask about language preference**: If the user hasn't specified R or Python, ask which they prefer before providing code examples158- Always frame responses using the five-question framework when appropriate159- Cite specific sections from summaries or manuals160- Mention `get_dataset()` when users need example data161- For mixed requests, start with conceptual framing then show implementation