Skip to content

Instantly share code, notes, and snippets.

@jebyrnes
Created December 8, 2020 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jebyrnes/150bdbc2b85f4d6ad530267d73c1f9d2 to your computer and use it in GitHub Desktop.
Save jebyrnes/150bdbc2b85f4d6ad530267d73c1f9d2 to your computer and use it in GitHub Desktop.
Shows how to use coefs and their vcov matrix to get simulated means and SE- will work for any model! And this example uses a categorical variable. Using the model.matrix avoids having to understand the treatment contrasts.
library(mvtnorm)
library(dplyr)
#make cyl a factor, like site
mtcars$cyl <- as.character(mtcars$cyl)
#fit a model
mod <- lm(mpg ~ cyl*hp, data = mtcars)
#get 10K draws of the coefficients
coef_sims <- rmvnorm(1e4, coef(mod), vcov(mod))
#10k rows by 6 cols
dim(coef_sims)
#now, let's get the site effect at the average level of HP
dat <- data.frame(cyl = unique(mtcars$cyl),
hp = mean(mtcars$hp),
mpg = 1:3) #just need some values
#ok, we need to turn this into a model frame
dat_frame <- model.matrix(mpg ~ cyl*hp, data = dat)
#the calculation!
mpg <- coef_sims %*% t(dat_frame)
#how many sims?
dim(mpg) #10k rows, 3 cols - 1 for each cyl
#add simulated predictions to data frame
dat$mpg <- colMeans(mpg)
dat$se_mpg <- apply(mpg, 2, sd)
#plot
library(ggplot2)
ggplot(dat,
aes(x = cyl, y = mpg, ymin = mpg-se_mpg, ymax = mpg+se_mpg)) +
geom_pointrange()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment