library(lme4) 
library(lmerTest)
library(performance)
library(ggeffects)
library(ggplot2)

## Import the data
library(haven)
pisa_hw1<- read_sav("C:/Users/Tingyen/OneDrive - 國立陽明交通大學/桌面/HLM/Data/PISA10/PISASchools10.sav")
View(pisa_hw1)

#第一題========================================

#描述性統計
library(psych)
describe(pisa_hw1$mathscor)
##    vars   n mean   sd median trimmed   mad   min  max range  skew kurtosis   se
## X1    1 176 49.7 9.07  49.76   49.83 10.53 25.73 70.6 44.88 -0.09    -0.58 0.68
describe(pisa_hw1$hedres)
##    vars   n mean   sd median trimmed  mad min  max range  skew kurtosis  se
## X1    1 176 6.42 1.37   6.37    6.62 1.96   1 7.69  6.69 -1.15     1.47 0.1
describe(pisa_hw1$acadpres)
##    vars   n mean   sd median trimmed  mad  min  max range  skew kurtosis   se
## X1    1 176 3.84 1.21   3.77    3.93 1.62 1.39 5.47  4.08 -0.54    -0.67 0.09
#長條圖
ggplot(pisa_hw1, aes(x = mathscor)) +
  geom_histogram(binwidth = 1, fill = "lightblue", color = "black") +
  labs(title = "Histogram of mathscor", x = "mathscor", y = "Frequency")

ggplot(pisa_hw1, aes(x = hedres)) +
  geom_histogram(binwidth = 1, fill = "lightblue", color = "black") +
  labs(title = "Histogram of hedres", x = "hedres", y = "Frequency")

ggplot(pisa_hw1, aes(x = acadpres)) +
  geom_histogram(binwidth = 1, fill = "lightblue", color = "black") +
  labs(title = "Histogram of acadpres", x = "acadpres", y = "Frequency")

#第二題========================================

#separate multiple regression models for each of the 10 schools

##select a school
table(pisa_hw1$schoolid)
## 
## 99104 99105 99109 99143 99153 99183 99192 99226 99243 99294 
##    13    18    18    18    17    17    20    19    18    18
school1 <- pisa_hw1[pisa_hw1$schoolid =="99104",]
sch.re1 <- lm(mathscor ~ hedres, data = school1)
summary(sch.re1)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school1)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -9.2428 -0.5065  2.1722  3.1181  4.2552 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   27.906      7.903   3.531  0.00471 **
## hedres         4.075      1.137   3.583  0.00430 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.922 on 11 degrees of freedom
## Multiple R-squared:  0.5386, Adjusted R-squared:  0.4966 
## F-statistic: 12.84 on 1 and 11 DF,  p-value: 0.004296
school2 <- pisa_hw1[pisa_hw1$schoolid =="99105",]
sch.re2 <- lm(mathscor ~ hedres, data = school2)
summary(sch.re2)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school2)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -6.970 -2.379 -0.621  2.534  7.737 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  29.1943     4.4796   6.517  7.1e-06 ***
## hedres        2.6122     0.7133   3.662   0.0021 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.137 on 16 degrees of freedom
## Multiple R-squared:  0.456,  Adjusted R-squared:  0.422 
## F-statistic: 13.41 on 1 and 16 DF,  p-value: 0.002104
school3 <- pisa_hw1[pisa_hw1$schoolid =="99109",]
sch.re3 <- lm(mathscor ~ hedres, data = school3)
summary(sch.re3)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school3)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.1105  -4.6845   0.2888   5.0606  13.0389 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   27.920      6.803   4.104 0.000829 ***
## hedres         2.640      1.065   2.478 0.024756 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.819 on 16 degrees of freedom
## Multiple R-squared:  0.2773, Adjusted R-squared:  0.2321 
## F-statistic: 6.139 on 1 and 16 DF,  p-value: 0.02476
school4 <- pisa_hw1[pisa_hw1$schoolid =="99143",]
sch.re4 <- lm(mathscor ~ hedres, data = school4)
summary(sch.re4)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -13.071  -4.752   1.542   5.179  11.816 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   85.653     12.698   6.745  4.7e-06 ***
## hedres        -4.619      1.836  -2.515    0.023 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.865 on 16 degrees of freedom
## Multiple R-squared:  0.2834, Adjusted R-squared:  0.2386 
## F-statistic: 6.327 on 1 and 16 DF,  p-value: 0.02295
school5 <- pisa_hw1[pisa_hw1$schoolid =="99153",]
sch.re5 <- lm(mathscor ~ hedres, data = school5)
summary(sch.re5)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school5)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -12.4872  -5.0836   0.6374   5.5814   8.3419 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)  
## (Intercept)    8.859     11.546   0.767   0.4548  
## hedres         5.242      1.788   2.932   0.0103 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.696 on 15 degrees of freedom
## Multiple R-squared:  0.3644, Adjusted R-squared:  0.322 
## F-statistic: 8.599 on 1 and 15 DF,  p-value: 0.0103
school6 <- pisa_hw1[pisa_hw1$schoolid =="99183",]
sch.re6 <- lm(mathscor ~ hedres, data = school6)
summary(sch.re6)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school6)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -6.299 -3.848  1.355  2.271  5.834 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)  
## (Intercept)   30.301     14.334   2.114   0.0517 .
## hedres         3.628      1.972   1.840   0.0857 .
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.067 on 15 degrees of freedom
## Multiple R-squared:  0.1841, Adjusted R-squared:  0.1297 
## F-statistic: 3.384 on 1 and 15 DF,  p-value: 0.0857
school7 <- pisa_hw1[pisa_hw1$schoolid =="99192",]
sch.re7 <- lm(mathscor ~ hedres, data = school7)
summary(sch.re7)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school7)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -12.009  -5.206   1.061   4.904   7.250 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  25.5161     5.2914   4.822 0.000137 ***
## hedres        2.8679     0.7956   3.605 0.002026 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.846 on 18 degrees of freedom
## Multiple R-squared:  0.4192, Adjusted R-squared:  0.387 
## F-statistic: 12.99 on 1 and 18 DF,  p-value: 0.002026
school8 <- pisa_hw1[pisa_hw1$schoolid =="99226",]
sch.re8 <- lm(mathscor ~ hedres, data = school8)
summary(sch.re8)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school8)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -12.4915  -3.4785   0.7235   4.6425  10.6648 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   70.318      5.951  11.817 1.27e-09 ***
## hedres        -3.076      1.003  -3.067  0.00698 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.189 on 17 degrees of freedom
## Multiple R-squared:  0.3562, Adjusted R-squared:  0.3183 
## F-statistic: 9.406 on 1 and 17 DF,  p-value: 0.006981
school9 <- pisa_hw1[pisa_hw1$schoolid =="99243",]
sch.re9 <- lm(mathscor ~ hedres, data = school9)
summary(sch.re9)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school9)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.9846  -5.7337   0.7941   5.1190  12.9151 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   23.350      8.854   2.637  0.01793 * 
## hedres         4.540      1.516   2.995  0.00858 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.021 on 16 degrees of freedom
## Multiple R-squared:  0.3592, Adjusted R-squared:  0.3191 
## F-statistic: 8.967 on 1 and 16 DF,  p-value: 0.008577
school10 <- pisa_hw1[pisa_hw1$schoolid =="99294",]
sch.re10 <- lm(mathscor ~ hedres, data = school10)
summary(sch.re10)
## 
## Call:
## lm(formula = mathscor ~ hedres, data = school10)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.1222  -4.0844   0.1293   4.1498  10.8107 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)  
## (Intercept)   28.789     10.340   2.784   0.0133 *
## hedres         3.749      1.480   2.533   0.0221 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.071 on 16 degrees of freedom
## Multiple R-squared:  0.2863, Adjusted R-squared:  0.2417 
## F-statistic: 6.418 on 1 and 16 DF,  p-value: 0.02213

#第三題========================================

#Model1:random-effects ANOVA model
re_ANOVA <- lmer(mathscor ~ (1|schoolid), data = pisa_hw1)
summary(re_ANOVA)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: mathscor ~ (1 | schoolid)
##    Data: pisa_hw1
## 
## REML criterion at convergence: 1232.9
## 
## Scaled residuals: 
##      Min       1Q   Median       3Q      Max 
## -2.29327 -0.66535  0.01497  0.65333  2.23111 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  schoolid (Intercept) 27.13    5.209   
##  Residual             58.19    7.628   
## Number of obs: 176, groups:  schoolid, 10
## 
## Fixed effects:
##             Estimate Std. Error     df t value Pr(>|t|)    
## (Intercept)   49.883      1.746  8.962   28.57 4.11e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
icc(re_ANOVA)
## # Intraclass Correlation Coefficient
## 
##     Adjusted ICC: 0.318
##   Unadjusted ICC: 0.318
ranova(re_ANOVA)
## ANOVA-like table for random-effects: Single term deletions
## 
## Model:
## mathscor ~ (1 | schoolid)
##                npar  logLik    AIC    LRT Df Pr(>Chisq)    
## <none>            3 -616.44 1238.9                         
## (1 | schoolid)    2 -636.86 1277.7 40.843  1   1.65e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#Model2:Random coefficients model with hedres (group-mean centered)
## Creating group-mean centered hedres 
library(dplyr) 
library(magrittr)

pisa_hw1 %<>% 
  group_by(schoolid) %>% 
  mutate(hedres_mean = mean(hedres)) #computing the group means, one for each school

pisa_hw1 %<>%
  mutate(hedres_cwc = hedres - hedres_mean) #creating group-mean centered variable

pisa_hw1 %>% 
  group_by(schoolid) %>% 
  summarize(
    mean(hedres_cwc)
  )
## # A tibble: 10 × 2
##    schoolid `mean(hedres_cwc)`
##       <dbl>              <dbl>
##  1    99104           6.83e-17
##  2    99105          -2.96e-16
##  3    99109          -2.96e-16
##  4    99143           2.47e-16
##  5    99153          -3.66e-16
##  6    99183           2.61e-16
##  7    99192           8.89e-17
##  8    99226           3.04e-16
##  9    99243          -2.47e-16
## 10    99294           2.47e-16
re_ANOVA_hedres_cwc <- lmer( mathscor~ 1 + hedres_cwc +(1+hedres_cwc|schoolid), data = pisa_hw1)
summary(re_ANOVA_hedres_cwc)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: mathscor ~ 1 + hedres_cwc + (1 + hedres_cwc | schoolid)
##    Data: pisa_hw1
## 
## REML criterion at convergence: 1186.7
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -2.6170 -0.6908  0.1315  0.6730  2.0353 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr 
##  schoolid (Intercept) 28.111   5.302         
##           hedres_cwc   9.101   3.017    -0.40
##  Residual             40.391   6.355         
## Number of obs: 176, groups:  schoolid, 10
## 
## Fixed effects:
##             Estimate Std. Error     df t value Pr(>|t|)    
## (Intercept)   49.882      1.744  8.974  28.595    4e-10 ***
## hedres_cwc     1.937      1.056  8.974   1.834   0.0999 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Correlation of Fixed Effects:
##            (Intr)
## hedres_cwc -0.348
ranova(re_ANOVA_hedres_cwc)
## ANOVA-like table for random-effects: Single term deletions
## 
## Model:
## mathscor ~ hedres_cwc + (1 + hedres_cwc | schoolid)
##                                           npar  logLik    AIC    LRT Df
## <none>                                       6 -593.36 1198.7          
## hedres_cwc in (1 + hedres_cwc | schoolid)    4 -609.52 1227.0 32.328  2
##                                           Pr(>Chisq)    
## <none>                                                  
## hedres_cwc in (1 + hedres_cwc | schoolid)  9.549e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
confint(re_ANOVA_hedres_cwc,oldNames=F)
##                                          2.5 %     97.5 %
## sd_(Intercept)|schoolid              3.2211193  8.6068634
## cor_hedres_cwc.(Intercept)|schoolid -0.8530466  0.3281002
## sd_hedres_cwc|schoolid               1.6627462  5.0648605
## sigma                                5.7109658  7.1329037
## (Intercept)                         46.3046487 53.4671296
## hedres_cwc                          -0.2371252  4.1229880
#Model3
#grand means
## Create a grand-mean centered version of acadppres, it's a new var "acadppres_cgm"
pisa_hw1$acadpres_cgm <- pisa_hw1$acadpres-3.8688
summary(pisa_hw1$acadpres_cgm)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -2.47880 -0.78629 -0.10110 -0.03261  1.03315  1.60285
library(psych)
describe(pisa_hw1$hedres_cwc)
##    vars   n mean   sd median trimmed  mad   min  max range  skew kurtosis  se
## X1    1 176    0 1.28   0.16     0.1 1.03 -5.44 1.99  7.43 -1.03        2 0.1
describe(pisa_hw1$acadpres_cgm)
##    vars   n  mean   sd median trimmed  mad   min max range  skew kurtosis   se
## X1    1 176 -0.03 1.21   -0.1    0.06 1.62 -2.48 1.6  4.08 -0.54    -0.67 0.09
CroLev1<- lmer( mathscor~ 1 + hedres_cwc+ acadpres_cgm+hedres_cwc*acadpres_cgm +(1+hedres_cwc|schoolid), data = pisa_hw1)
summary(CroLev1)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: 
## mathscor ~ 1 + hedres_cwc + acadpres_cgm + hedres_cwc * acadpres_cgm +  
##     (1 + hedres_cwc | schoolid)
##    Data: pisa_hw1
## 
## REML criterion at convergence: 1167.5
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -2.5489 -0.7331  0.1242  0.6339  2.0463 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr 
##  schoolid (Intercept)  2.999   1.732         
##           hedres_cwc   9.269   3.044    -0.25
##  Residual             40.366   6.353         
## Number of obs: 176, groups:  schoolid, 10
## 
## Fixed effects:
##                         Estimate Std. Error      df t value Pr(>|t|)    
## (Intercept)              49.8639     0.7285  8.2004  68.449 1.33e-12 ***
## hedres_cwc                1.9554     1.0673  7.7678   1.832 0.105412    
## acadpres_cgm              3.9401     0.5979  8.4144   6.590 0.000136 ***
## hedres_cwc:acadpres_cgm  -0.7804     0.8993  8.6761  -0.868 0.408892    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Correlation of Fixed Effects:
##             (Intr) hdrs_c acdpr_
## hedres_cwc  -0.170              
## acadprs_cgm  0.013  0.000       
## hdrs_cwc:c_  0.000  0.059 -0.163
ranova(CroLev1)
## ANOVA-like table for random-effects: Single term deletions
## 
## Model:
## mathscor ~ hedres_cwc + acadpres_cgm + (1 + hedres_cwc | schoolid) + hedres_cwc:acadpres_cgm
##                                           npar  logLik    AIC    LRT Df
## <none>                                       8 -583.76 1183.5          
## hedres_cwc in (1 + hedres_cwc | schoolid)    6 -595.36 1202.7 23.205  2
##                                           Pr(>Chisq)    
## <none>                                                  
## hedres_cwc in (1 + hedres_cwc | schoolid)  9.143e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
confint(CroLev1, oldNames = F)
##                                          2.5 %     97.5 %
## sd_(Intercept)|schoolid              0.0000000  3.0814541
## cor_hedres_cwc.(Intercept)|schoolid -1.0000000  1.0000000
## sd_hedres_cwc|schoolid               1.4815514  4.8336640
## sigma                                5.7078166  7.1268645
## (Intercept)                         48.4548248 51.2795928
## hedres_cwc                          -0.1103794  4.0478814
## acadpres_cgm                         2.7809470  5.0961322
## hedres_cwc:acadpres_cgm             -2.5032560  0.9751319
library(sjPlot)
tab_model(re_ANOVA,re_ANOVA_hedres_cwc,CroLev1,show.dev=TRUE,show.ci=F,show.r2=F,show.icc=F)
  math PISA score math PISA score math PISA score
Predictors Estimates p Estimates p Estimates p
(Intercept) 49.88 <0.001 49.88 <0.001 49.86 <0.001
hedres cwc 1.94 0.068 1.96 0.069
school academic press 3.94 <0.001
hedres_cwc:acadpres_cgm -0.78 0.387
Random Effects
σ2 58.19 40.39 40.37
τ00 27.13 schoolid 28.11 schoolid 3.00 schoolid
τ11   9.10 schoolid.hedres_cwc 9.27 schoolid.hedres_cwc
ρ01   -0.40 schoolid -0.25 schoolid
N 10 schoolid 10 schoolid 10 schoolid
Observations 176 176 176
Deviance 1235.830 1191.468 1173.022