#LAB 8 CLASS library(lme4) library(tidyverse) library(broom)
data(‘sleepstudy’) head(sleepstudy) ?sleepstudy
class(sleepstudy\(Days) #to check the class of this variable sleepstudy\)Days <- as.numeric(as.character(sleepstudy$Days)) #to ensure that it #is as numeric
#plot with respect to the 10 days of the experiment
ggplot(sleepstudy, aes(x = factor(Days), y = Reaction)) + geom_boxplot(colour = “darkblue”) + labs(title = “Reaction Times Across Days for Each Day”, x = “Days of Sleep Deprivation”, y = “Reaction Time (ms)”)
ggplot(sleepstudy, aes(x = Days, y = Reaction)) + geom_point()
+
geom_line(aes(group = Subject), color = “blue”) +
facet_wrap(~ Subject, ncol = 6) +
labs(title = “Reaction Times Across Days for Each Participant”, x =
“Days of Sleep Deprivation”, y = “Reaction Time (ms)”) +
theme_minimal()
summary(sleepstudy\(Reaction) #to compute summary statics for the relevant variable summary(sleepstudy\)Days) summary(sleepstudy)
#but we need to change the baseline to the 3rd day because the effects of #sleep deprivition starts from there
sleepstudy2 <- sleepstudy[sleepstudy$Days >= 2, ]
#to account for the multiple data from single subject, we have to use the mixed #models here
#fit a mixed effect model that accounts for the multiple data from both #subjects and with respect to days too
model <- lmer(Reaction ~ Days + (1 + Days | Subject), data = sleepstudy2)
summary(model)
#Random effects: # Groups Name Variance Std.Dev. Corr #Subject
(Intercept) 1473.60 38.387
#Days 42.03 6.483 -0.31 #Residual 689.25 26.254
#Number of obs: 126, groups: Subject, 18
#Fixed effects: # Estimate Std. Error t value #(Intercept) 247.702 11.686 21.20 #Days 11.063 1.924 5.75
#checking the residuals of the model
res <- residuals(model)
par(mfrow = c(1, 3))
hist(res)
qqnorm(res) qqline(res)
plot(fitted(model),res)