I'm struggling replicating the results given by avg_comparisons
.
What am I doing wrong?
library(marginaleffects)
dat <- get_dataset("thornton")
mod <- glm(outcome ~ incentive * (agecat + distance),
data = dat, family = binomial)
avg_comparisons(mod, variables = "incentive")$estimate
# 0.451920016659
# Counterfactual predictions
mydf <- dat
mydf$incentive <- 1
mydf$pred1 <- predict(mod, newdata = mydf, type = "response")
mydf$incentive <- 0
mydf$pred0 <- predict(mod, newdata = mydf, type = "response")
mean(mydf$pred1-mydf$pred0, na.rm=TRUE)
# 0.45174545593
There are missing data in your data frames. Call na.omit()
first and your code will replicate the results exactly.