Last active
January 19, 2017 22:23
-
-
Save benwhalley/8686bdf8c80550a089f135ee303d7c5f to your computer and use it in GitHub Desktop.
Using sims from predictInterval to plot intervals around continuous covariate
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
library(lmerTest) | |
library(merTools) | |
library(tidyverse) | |
# linear model | |
m <- lmer(Reaction~Days*I(Days^2)+(1|Subject), data=sleepstudy) | |
newdata = expand.grid(Reaction=NA, Days=1:5, Subject=Inf) %>% as.data.frame | |
sims <- predictInterval(m, newdata=newdata, returnSims = T) | |
bind_sims(attr(sims, 'sim.results'), newdata) %>% | |
ggplot(aes(Days, fitted)) + geom_smooth(method="loess") | |
# logit model | |
require("HSAUR2") | |
# run a raw plot first to sanity check against | |
rawplot <- toenail %>% | |
ggplot(aes(visit, as.numeric(outcome=="moderate or severe"), group=treatment, color=treatment)) + | |
geom_smooth() | |
rawplot | |
m2 <- glmer(outcome~treatment*visit+(1|patientID), | |
data=toenail, | |
family=binomial) | |
toenail %>% glimpse | |
newdata2 = expand.grid(outcome=NA, treatment=c("terbinafine", "itraconazole"), patientID=Inf, visit=seq(1,5, by=.25)) | |
sims2 <- predictInterval(m2, newdata=newdata2, returnSims = T) | |
modelplot <- bind_sims(attr(sims2, 'sim.results'), newdata2) %>% | |
ggplot(aes(visit, exp(fitted), group=treatment, color=forcats::fct_rev(treatment))) + geom_smooth() | |
modelplot | |
# now can calulate and plot some other quantity - eg difference between treatments | |
diffplot <- bind_sims(attr(sims2, 'sim.results'), newdata2) %>% | |
dcast(sim+visit~treatment) %>% | |
mutate(diff=exp(terbinafine - itraconazole)) %>% | |
ggplot(aes(visit, diff)) + geom_smooth() | |
diffplot | |
# combine raw, model predicted group, and difference plots | |
grid.arrange( | |
rawplot + theme(legend.position="bottom"), | |
modelplot + theme(legend.position="bottom"), | |
diffplot +theme(legend.position="bottom"), | |
nrow=3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment