Created
August 11, 2020 17:52
-
-
Save jebyrnes/cd392d7a6b75709298bb7122a831f121 to your computer and use it in GitHub Desktop.
Predictions of models with nominal or continuous variables using predictInterval and lmer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#fit a model | |
library(lme4) | |
sleepstudy$c_Days <- as.character(sleepstudy$Days) | |
#same model, one continuous, one nominal | |
m1_c <- lmer(Reaction ~ Days + (1 | Subject), sleepstudy) | |
m1_n <- lmer(Reaction ~ c_Days + (1 | Subject), sleepstudy) | |
#Making data grid with nominal variables | |
library(modelr) | |
#make a new data set | |
new_c <- data_grid(data = sleepstudy, | |
Days = seq_range(Days, 2), | |
Subject = levels(Subject)[1]) #when you have a factor, you use levels instead of unique | |
#Subject = unique(Subject)[1]) #if subject had been a character | |
new_n <- data_grid(data = sleepstudy, | |
c_Days = unique(c_Days), | |
Subject = levels(Subject)[1]) | |
#making the predictions with a confidence interval | |
#https://cran.r-project.org/web/packages/merTools/vignettes/Using_predictInterval.html | |
library(merTools) | |
pred_c <- predictInterval(m1_c, newdata = new_c, | |
which = "fixed") | |
pred_c <- pred_c %>% | |
dplyr::bind_cols(new_c) | |
#nominal prediction | |
pred_n <- predictInterval(m1_n, newdata = new_n, | |
which = "fixed") | |
pred_n <- pred_n %>% | |
dplyr::bind_cols(new_n) | |
#plot | |
library(ggplot2) | |
ggplot() + | |
geom_point(data = sleepstudy, | |
aes(x = Days, y = Reaction, | |
color = Subject)) + | |
geom_line(data = pred_c, | |
aes(x = Days, y = fit)) + | |
geom_ribbon(data = pred_c, | |
aes(x = Days, | |
ymin = lwr, | |
ymax = upr), | |
alpha = 0.1) + | |
theme_bw() | |
#nominal plot | |
ggplot() + | |
geom_point(data = sleepstudy, | |
aes(x = c_Days, y = Reaction, | |
color = Subject, group = Subject)) + | |
geom_line(data = pred_n, | |
aes(x = c_Days, y = fit, group = Subject)) + | |
geom_point(data = pred_n, | |
aes(x = c_Days, y = fit, group = Subject)) + | |
geom_linerange(data = pred_n, | |
aes(x = c_Days, | |
ymin = lwr, | |
ymax = upr, group = Subject)) + | |
theme_bw() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment