library(marginaleffects)
# simple marginal means for each level of `cyl`
dat <- mtcars
dat$carb <- factor(dat$carb)
dat$cyl <- factor(dat$cyl)
dat$am <- as.logical(dat$am)
mod <- lm(mpg ~ carb + cyl + am, dat)
marginalmeans(
mod,
variables = "cyl")
# collapse levels of cyl by averaging
by <- data.frame(
cyl = c(4, 6, 8),
by = c("4 & 6", "4 & 6", "8"))
marginalmeans(mod,
variables = "cyl",
by = by)
# pairwise differences between collapsed levels
marginalmeans(mod,
variables = "cyl",
by = by,
hypothesis = "pairwise")
# cross
marginalmeans(mod,
variables = c("cyl", "carb"),
cross = TRUE)
# collapsed cross
by <- expand.grid(
cyl = unique(mtcars$cyl),
carb = unique(mtcars$carb))
by$by <- ifelse(
by$cyl == 4,
paste("Control:", by$carb),
paste("Treatment:", by$carb))
# Convert numeric variables to categorical before fitting the model
dat <- mtcars
dat$am <- as.logical(dat$am)
dat$carb <- as.factor(dat$carb)
mod <- lm(mpg ~ hp + am + carb, data = dat)
# Compute and summarize marginal means
mm <- marginalmeans(mod)
summary(mm)
# Contrast between marginal means (carb2 - carb1), or "is the 1st marginal means equal to the 2nd?"
# see the vignette on "Hypothesis Tests and Custom Contrasts" on the `marginaleffects` website.
lc <- c(-1, 1, 0, 0, 0, 0)
marginalmeans(mod, variables = "carb", hypothesis = "b2 = b1")
marginalmeans(mod, variables = "carb", hypothesis = lc)
# Multiple custom contrasts
lc <- matrix(c(
-2, 1, 1, 0, -1, 1,
-1, 1, 0, 0, 0, 0
),
ncol = 2,
dimnames = list(NULL, c("A", "B")))
marginalmeans(mod, variables = "carb", hypothesis = lc)
Run the code above in your browser using DataLab