gavinsimpson / gratia

ggplot-based graphics and useful functions for GAMs fitted using the mgcv package
https://gavinsimpson.github.io/gratia/
Other
206 stars 28 forks source link

posterior_samples & co need to handle offsets correctly #233

Closed gavinsimpson closed 1 year ago

gavinsimpson commented 1 year ago

When type = "lpmatrix", which is how fitted_samples() etc uses predict.gam(), predict.gam() doesn't include the offset in the Xp matrix. Instead, predict.gam() returns the Xp matrix with an attribute model.offset containing the vector of values for the offset term:

> Xp <- predict(mod, type = "lpmatrix")
> head(attr(Xp, "model.offset"))                                              
[1] 6.907755 6.906755 6.907755 6.908755 6.907755 6.908755

So, modify the line

sims <- Xp %*% t(betas)

to be

sims <- (Xp %*% t(betas)) + attr(Xp, "model.offset")

Originally posted by @gavinsimpson in https://github.com/gavinsimpson/gratia/discussions/231#discussioncomment-6719974