ggplot2 - get predictions and confidence intervals when using lmer, help needed.

396 views
Skip to first unread message

Ron Stone

unread,
Jul 12, 2013, 2:37:28 AM7/12/13
to ggp...@googlegroups.com
Dear all,
My goal has been to get predictions and confidence intervals when using lmer.
To achieve this I have used ggplot2, by modifying an existing script (http://glmm.wikidot.com/faq). I wonder if I have specified the second random effect properly, se below (font colour "orange")
1. Is my second random effect written correctly?
2. Is it possible to get confidence bands instead of error bars around the predicted regression line (geom_errorbar)?
I have the following model:
Speed = fixed effect (continous)
BodyMass = fixed effect (continous)
ID = random effect
Species = random effect.
lmerfit1<-(Speed~BodyMass+(1|ID)+(1|Species))
From this I would like to make a regression curve with confidence intervals (bands), showing the effect of BodyMass on Speed.
library(lme4)
library(ggplot2) # Plotting
fm1 <- lmer(
    formula = Speed ~ BodyMass + (1|ID)
+(1|Species), data = Flight)
newdat <- expand.grid(
BodyMass = seq(from = 0, to = 20, by = 1), Speed = 0
)
mm <- model.matrix(terms(fm1),newdat)
newdat$Speed <- mm %*% fixef(fm1)
pvar1 <- diag(mm %*% tcrossprod(vcov(fm1),mm))
tvar1 <- pvar1+VarCorr(fm1)$ID[1] +  VarCorr(fm1)$Species[1]  ## must be adapted for more complex models
newdat <- data.frame(
    newdat
    , plo = newdat$Speed-2*sqrt(pvar1)
    , phi = newdat$dSpeed+2*sqrt(pvar1)
    , tlo = newdat$Speed-2*sqrt(tvar1)
    , thi = newdat$Speed+2*sqrt(tvar1)
)
#plot confidence
g0 <- ggplot(newdat, aes(x=aBodyMass, y=Speed))+geom_point()
g0 + geom_errorbar(aes(ymin = plo, ymax = phi))+
    opts(title="CI based on fixed-effects uncertainty ONLY")
#plot prediction
g0 + geom_errorbar(aes(ymin = tlo, ymax = thi))+
    opts(title="CI based on FE uncertainty + RE variance")
Reply all
Reply to author
Forward
0 new messages