Posts Tagged ‘confidence’

Predictions and/or confidence (or prediction) intervals on predictions

Tuesday, May 25th, 2010

Los intervalos de confianza de la funcion predict nos han dado muchos quebraderos de cabeza!
El codigo calcula los intervalos de confianza de los fitted values de los predict !!

library(nlme) 
fm1 <- lme(distance ~ age*Sex, random = ~ 1 + age | Subject, data = Orthodont) 
 
plot(Orthodont)
newdat <- expand.grid(age=c(8,10,12,14), Sex=c("Male","Female")) 
 
newdat$pred <- predict(fm1, newdat, level = 0)
 
Designmat <- model.matrix(eval(eval(fm1$call$fixed)[-2]), newdat[-3]) 
predvar <- diag(Designmat %*% fm1$varFix %*% t(Designmat)) 
newdat$SE <- sqrt(predvar) 
 
newdat$SE2 <- sqrt(predvar+fm1$sigma^2)
 
library(ggplot2) 
pd <- position_dodge(width=0.4) 
ggplot(newdat,aes(x=age,y=pred,colour=Sex))+ 
   geom_point(position=pd)+ 
  geom_linerange(aes(ymin=pred-2*SE,ymax=pred+2*SE), position=pd)
 
 
## prediction intervals 
ggplot(newdat,aes(x=age,y=pred,colour=Sex))+ 
   geom_point(position=pd)+ 
   geom_linerange(aes(ymin=pred-2*SE2,ymax=pred+2*SE2), position=pd)

Fuente: Wikidot