Using the Seatbelts (included in R) data, I want the predictions for the marginal effect of "front". This variable has 170 values. ggeffect()
is only returning predictions for front at the values 400, 500, 600, ...,1300. How can I return all of the predictions?
Seatbelts <- data.frame(Seatbelts)
head(Seatbelts)
Seatbelts <- Seatbelts[complete.cases(Seatbelts), ]
## 75% of the sample size
smp_size <- floor(0.75 * nrow(Seatbelts))
## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Seatbelts)), size = smp_size)
train <- Seatbelts[train_ind, ]
test <- Seatbelts[-train_ind, ]
# glm()
m1 <- glm(DriversKilled ~ front + rear + kms + PetrolPrice +
VanKilled + law,
family=poisson(link = "log"),
weights = drivers,
data=train)
ggeffect(m1, terms = c("front"), typical = "average")
Under the hood, the function ggeffect
uses the Effect
function from the effects
library to get its data for plotting. If you are interested in seeing the actual numbers predicted at various levels of a particular variable it would be best to get them directly, since it is not the job of ggeffect
to return an arbitrary list of predictions.
We can get a nice data frame of the prediction and confidence interval at any levels you choose by passing them via the xlevels
parameter.
predictions <- effects::Effect("front", m1, xlevels = list(front = seq(400, 1300, 5)))
df <- data.frame(front = predictions$x,
fit = exp(predictions$fit),
lower = exp(predictions$lower),
upper = exp(predictions$upper))
So the top of our data frame looks like this:
head(df)
#> front fit lower upper
#> 1 400 68.16168 67.99573 68.32803
#> 2 405 68.62226 68.45703 68.78788
#> 3 410 69.08595 68.92146 69.25083
#> 4 415 69.55277 69.38904 69.71689
#> 5 420 70.02275 69.85979 70.18609
#> 6 425 70.49590 70.33373 70.65845
Created on 2022-03-01 by the reprex package (v2.0.1)