Skip to content

Instantly share code, notes, and snippets.

@chrishanretty
Last active September 26, 2024 07:56
Show Gist options
  • Save chrishanretty/47df9ccf31010f837224f6fc68a222c1 to your computer and use it in GitHub Desktop.
Save chrishanretty/47df9ccf31010f837224f6fc68a222c1 to your computer and use it in GitHub Desktop.
Two different ways of calculating "average effects" in conditional logit models
### Purpose of this code: estimate a conditional logit model, and
### calculate the average effect of changing one non-induced
### observation in each stratum to an induced observation.
library(survival)
library(marginaleffects)
data("infert")
## Create a subset, and identify a non-induced observation as a
## "focal" observation for which we will later change the value
infert2 <- infert |>
filter(induced %in% c(0, 1)) |>
mutate(randno = rnorm(n())) |>
group_by(stratum) |>
arrange(induced, randno) |>
mutate(focal = c(1, rep(0, n() - 1))) |>
as.data.frame()
## Estimate the model
mod <- mclogit(cbind(case, stratum) ~ spontaneous + induced,
data = infert2)
## Create a data frame with alternative specifications
altspec <- data.frame(
low = infert2$induced,
high = ifelse(infert2$focal, 1, infert2$induced)
)
## Calculate the marginal effect one way
## averaging over values of focal
marg_fx <- comparisons(mod,
newdata = infert2,
variables = list(induced = altspec),
type = "response",
by = "focal")
## Term Contrast focal Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
## induced custom 0 0.065 0.0211 3.08 0.00206 8.9 0.0237 0.106
## induced custom 1 -0.104 0.0339 -3.08 0.00206 8.9 -0.1707 -0.038
### Now calculate changes in predicted probabilities manually
p1 <- marginaleffects::predictions(mod,
newdata = infert2,
type = "response")
p2 <- marginaleffects::predictions(mod,
newdata = infert2 |>
mutate(induced = ifelse(focal, 1, induced)),
type = "response")
p1 <- p1 |> filter(focal == 1) |> pull(estimate)
p2 <- p2 |> filter(focal == 1) |> pull(estimate)
## This value is much greater than what is shown above
## difference in probabilities of 18 percentage points
## compared to difference of 10 percentage points
mean(p1 - p2)
## [1] -0.1795952
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment