Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GarrettMooney/09910f2351a2008d736a234e08aed28f to your computer and use it in GitHub Desktop.
Save GarrettMooney/09910f2351a2008d736a234e08aed28f to your computer and use it in GitHub Desktop.
Predict for multiple models using linear algebra.
library(purrr)
# two regressions
lm_fit <- lm(mpg ~ wt + cyl, data = mtcars)
bayes_fit <- rstanarm::stan_glm(mpg ~ wt + cyl, data = mtcars)
# design matrix [32 x 3]
X <- model.matrix(lm_fit)
# coefficient matrix [3 x 2]
B <- list(lm = lm_fit, bayes = bayes_fit) %>%
map_dfc(coef) %>%
as.matrix()
# predictions [32 x 2]
X %*% B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment