# Modèle Linéare Mixte
library(lme4)
## Loading required package: Matrix
## Loading required package: Rcpp
# xyplot()
library(lattice)
# Charge les donnees 
data(sleepstudy)
#
#Dimension
#
dim(sleepstudy)
## [1] 180   3
#Name of the covariates
colnames(sleepstudy)
## [1] "Reaction" "Days"     "Subject"
#
#Nombre d'individus
#
length(unique(sleepstudy$Subject))
## [1] 18
#
# Nombres d'observations par individu 
# 
table(sleepstudy$Subject)
## 
## 308 309 310 330 331 332 333 334 335 337 349 350 351 352 369 370 371 372 
##  10  10  10  10  10  10  10  10  10  10  10  10  10  10  10  10  10  10
#
# Données Brutes 
#
plot(sleepstudy$Days,sleepstudy$Reaction)

#
# Recodage pour pouvoir dessiner les trajectoire individuelles 
#
# reshape() tres utile !!!
#
sleep2 <- reshape(sleepstudy, v.names="Reaction", idvar="Subject", timevar="Days", direction="wide")
#
# Dessiner les trajectoires 
#
matplot(0:9, t(sleep2[,-1]), type="b", pch=20, lty=1,xlab='Days',ylab='Reaction Time (ms)')

#
# Données individuelles + un modele lineaire (ne tient pas compte de la correlation intra)
# 
xyplot(Reaction ~ Days | Subject, sleepstudy, aspect = "xy",
       layout = c(9,2), type = c("g", "p", "r"),
       index.cond = function(x,y) coef(lm(y ~ x))[1],
       xlab = "Days of sleep deprivation",
       ylab = "Average reaction time (ms)")