if (FALSE) { # interactive()
}
mod <- glm(am ~ hp * wt, data = mtcars, family = binomial)
mfx <- marginaleffects(mod)
head(mfx)
# Average Marginal Effect (AME)
summary(mfx)
tidy(mfx)
plot(mfx)
# Marginal Effect at the Mean (MEM)
marginaleffects(mod, newdata = datagrid())
# Marginal Effect at User-Specified Values
# Variables not explicitly included in `datagrid()` are held at their means
marginaleffects(mod,
newdata = datagrid(hp = c(100, 110)))
# Group-Average Marginal Effects (G-AME)
# Calculate marginal effects for each observation, and then take the average
# marginal effect within each subset of observations with different observed
# values for the `cyl` variable:
mod2 <- lm(mpg ~ hp * cyl, data = mtcars)
mfx2 <- marginaleffects(mod2, variables = "hp", by = "cyl")
summary(mfx2)
# Marginal Effects at User-Specified Values (counterfactual)
# Variables not explicitly included in `datagrid()` are held at their
# original values, and the whole dataset is duplicated once for each
# combination of the values in `datagrid()`
mfx <- marginaleffects(mod,
newdata = datagrid(hp = c(100, 110),
grid_type = "counterfactual"))
head(mfx)
# Heteroskedasticity robust standard errors
marginaleffects(mod, vcov = sandwich::vcovHC(mod))
# hypothesis test: is the `hp` marginal effect at the mean equal to the `drat` marginal effect
mod <- lm(mpg ~ wt + drat, data = mtcars)
marginaleffects(
mod,
newdata = "mean",
hypothesis = "wt = drat")
# same hypothesis test using row indices
marginaleffects(
mod,
newdata = "mean",
hypothesis = "b1 - b2 = 0")
# same hypothesis test using numeric vector of weights
marginaleffects(
mod,
newdata = "mean",
hypothesis = c(1, -1))
# two custom contrasts using a matrix of weights
lc <- matrix(c(
1, -1,
2, 3),
ncol = 2)
colnames(lc) <- c("Contrast A", "Contrast B")
marginaleffects(
mod,
newdata = "mean",
hypothesis = lc)
Run the code above in your browser using DataLab