library(tidyverse)
library(broom)
library(table1)
library(car)
library(GGally)
library(easystats)
library(modelsummary)
library(gt)
library(lme4)
library (datawizard)
library(lmerTest)
library(modelsummary)
library(broom)
install.packages("Matrix")
install.packages("lme4")
library(lme4)
library(Matrix)
finches <- read_rds("data/geospiza.rds")

Exercise 1

Create a table1 and use GGally::ggpairs to explore your data.

conirostris
(N=185)
difficilis
(N=102)
fortis
(N=510)
fuliginosa
(N=318)
magnirostris
(N=90)
scandens
(N=229)
Overall
(N=1434)
Beak height (mm)
Mean (SD) 14.9 (1.63) 8.17 (0.494) 12.3 (1.29) 8.00 (0.508) 19.9 (1.83) 9.56 (0.584) 11.4 (3.39)
Median [Min, Max] 15.0 [10.5, 18.7] 8.10 [7.10, 9.70] 12.0 [8.60, 16.6] 8.00 [6.70, 10.2] 20.0 [11.5, 23.2] 9.60 [8.20, 11.9] 11.0 [6.70, 23.2]
Wing (length) (mm)
Mean (SD) 77.3 (2.94) 64.7 (3.35) 69.9 (3.45) 61.9 (2.39) 81.4 (3.92) 70.6 (2.20) 69.5 (6.36)
Median [Min, Max] 77.0 [68.0, 84.0] 64.0 [58.0, 71.0] 70.0 [60.0, 80.0] 62.0 [55.0, 70.0] 81.0 [70.0, 89.0] 71.0 [65.0, 76.0] 70.0 [55.0, 89.0]
Upper beak (mm)
Mean (SD) 21.0 (1.24) 13.8 (0.720) 16.5 (1.21) 12.5 (0.649) 22.8 (1.64) 19.6 (1.09) 16.9 (3.42)
Median [Min, Max] 21.0 [18.1, 24.1] 13.8 [12.3, 15.5] 16.3 [13.4, 20.2] 12.5 [11.0, 15.0] 22.9 [15.0, 25.9] 19.6 [17.1, 22.5] 16.6 [11.0, 25.9]
Sex
F 59 (31.9%) 29 (28.4%) 155 (30.4%) 128 (40.3%) 29 (32.2%) 72 (31.4%) 472 (32.9%)
M 126 (68.1%) 73 (71.6%) 355 (69.6%) 190 (59.7%) 61 (67.8%) 157 (68.6%) 962 (67.1%)

###GGpairs

 #GGpairs to explore data
cols_to_explore <- c(1,3,4,5,6)

# Select only the columns you want to explore from your dataset

data_subset <- finches[, cols_to_explore]

# Set up the GGpairs plot
ggpairs(
  data_subset,
  title = "Association Between Different Variables",
  mapping = ggplot2::aes(color = islandid),
  upper = list(
    continuous = "density", 
    combo = "facethist", 
    discrete = "colbar"
  ),
  lower = list(
    continuous = "cor", 
    combo = NULL
  ),
  diag = list(
    continuous = wrap("densityDiag", colour = NA, alpha = 0.6), 
    discrete = "densityDiag"
  ),
  legend = c(3, 5),
  showStrips = FALSE,
  cardinality_threshold = 6
) + 
labs(color = "Species") + 
theme_minimal() + 
theme(legend.position = "bottom",text = element_text(size = 16, family = "Arial"), # Adjust text size and font family
      axis.text.x = element_text(size = 12, angle = 45, hjust = 1), # Adjust x-axis text size and rotation
      axis.text.y = element_text(size = 12))
## Warning: `stat_contour()`: Zero contours were generated
## Warning in min(x): no non-missing arguments to min; returning Inf
## Warning in max(x): no non-missing arguments to max; returning -Inf
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: `stat_contour()`: Zero contours were generated
## Warning in min(x): no non-missing arguments to min; returning Inf
## Warning in max(x): no non-missing arguments to max; returning -Inf
## Warning: `stat_contour()`: Zero contours were generated
## Warning in min(x): no non-missing arguments to min; returning Inf
## Warning in max(x): no non-missing arguments to max; returning -Inf
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: `stat_contour()`: Zero contours were generated
## Warning in min(x): no non-missing arguments to min; returning Inf
## Warning in max(x): no non-missing arguments to max; returning -Inf
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Exercise 2

Question:Try to replicate as many graphs as you can from those shown above, and try to explain what could be the limitations of a fixed effects models we created

Plot 1:

ggplot(finches, aes(wingl, beakh)) +
  geom_point(aes(colour = species)) +
  geom_smooth(method = "lm", color = "grey") +
  theme_bw() +
  labs(x = "Wing length (mm)", y = "Beak height (mm)")

Plot 2:

m1 <- lm(beakh ~ wingl, finches)

ggplot(finches, aes(wingl, beakh)) +
  geom_point(alpha= 0.2, (aes(color = species))) +
  geom_smooth(
    data = augment(m1), 
    aes(x=wingl, y = beakh), 
    method = "lm",
    color = "grey") + 
  facet_wrap(~species, scales= "free_x") +
  labs(x = "Wing length (mm)", y = "Beak height (mm)")+
  theme_bw()

Plot3:

M1 <- lm(beakh ~ wingl, finches)
summary(M1)
## 
## Call:
## lm(formula = beakh ~ wingl, data = finches)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.9257 -1.0104  0.0236  1.0507  6.1625 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -20.397361   0.503009  -40.55   <2e-16 ***
## wingl         0.457641   0.007204   63.53   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.734 on 1432 degrees of freedom
## Multiple R-squared:  0.7381, Adjusted R-squared:  0.7379 
## F-statistic:  4035 on 1 and 1432 DF,  p-value: < 2.2e-16
finches <- 
  finches |> mutate(.resid = augment(M1)$.resid)

finches|> 
 ggplot(aes(wingl, .resid))+
  geom_point(aes(color = species), alpha = 0.2)+
  geom_hline(yintercept = 0, lty = 2)+
  facet_wrap(~species, scale= "free_x") + 
   labs(x = "Wing length (mm)", y = "residuals") +
   theme_bw()

Plot 4:

M3 <- lm(beakh ~  wingl + species + wingl:species, data = finches)
augment(M3)
## # A tibble: 1,434 × 9
##    beakh wingl species .fitted .resid    .hat .sigma   .cooksd .std.resid
##    <dbl> <dbl> <chr>     <dbl>  <dbl>   <dbl>  <dbl>     <dbl>      <dbl>
##  1  10.8    69 fortis     12.1 -1.27  0.00209  0.870 0.000374      -1.46 
##  2  10.3    65 fortis     11.1 -0.766 0.00592  0.870 0.000387      -0.883
##  3  10      65 fortis     11.1 -1.07  0.00592  0.870 0.000750      -1.23 
##  4   9.5    68 fortis     11.8 -2.32  0.00255  0.868 0.00152       -2.67 
##  5  11      66 fortis     11.3 -0.317 0.00447  0.870 0.0000500     -0.366
##  6  10.4    68 fortis     11.8 -1.42  0.00255  0.869 0.000570      -1.63 
##  7  11.3    67 fortis     11.6 -0.269 0.00335  0.870 0.0000268     -0.309
##  8  10.6    69 fortis     12.1 -1.47  0.00209  0.869 0.000501      -1.69 
##  9  10.8    67 fortis     11.6 -0.769 0.00335  0.870 0.000219      -0.885
## 10  10.3    68 fortis     11.8 -1.52  0.00255  0.869 0.000653      -1.75 
## # ℹ 1,424 more rows
augment(M3) %>% 
  ggplot(aes(wingl, beakh, color = species)) + 
  geom_point(alpha=.3) + 
  labs(x = "Wing Lenght (mm)", y = "Beak Height (mm)", 
       subtitle = "Intercepts and slopes are calculated separatly for each species") +
  geom_smooth(method = "lm", se= FALSE) +
   theme_bw() + 
ggtitle("Fixed Effects: intercepts and slopes")

Plot 5:

M2 <- lm(beakh~ wingl + species, data=finches)
augment(M2) %>% 
 ggplot(aes(wingl, .resid)) +
  geom_point(aes(color = species), alpha =0.4) +
  geom_hline(yintercept = 0, lty =2, linetype = "dashed") +
  facet_wrap(~species, scales = "free_x") +
  labs(x = "Wing Length (mm)", y = "residuals") +
   theme_bw()

Plot 6:

finches |> 
  ggplot(aes(wingl, beakh, color = species)) + 
  geom_point(alpha=0.3) + 
  geom_smooth(method="lm") + 
  labs(x = "Wing Length (mm)", y = "residuals")+
  theme_minimal()

Plot 7:

M3 <- lm(beakh ~  wingl + species + wingl:species, data = finches)

augment(M3)
## # A tibble: 1,434 × 9
##    beakh wingl species .fitted .resid    .hat .sigma   .cooksd .std.resid
##    <dbl> <dbl> <chr>     <dbl>  <dbl>   <dbl>  <dbl>     <dbl>      <dbl>
##  1  10.8    69 fortis     12.1 -1.27  0.00209  0.870 0.000374      -1.46 
##  2  10.3    65 fortis     11.1 -0.766 0.00592  0.870 0.000387      -0.883
##  3  10      65 fortis     11.1 -1.07  0.00592  0.870 0.000750      -1.23 
##  4   9.5    68 fortis     11.8 -2.32  0.00255  0.868 0.00152       -2.67 
##  5  11      66 fortis     11.3 -0.317 0.00447  0.870 0.0000500     -0.366
##  6  10.4    68 fortis     11.8 -1.42  0.00255  0.869 0.000570      -1.63 
##  7  11.3    67 fortis     11.6 -0.269 0.00335  0.870 0.0000268     -0.309
##  8  10.6    69 fortis     12.1 -1.47  0.00209  0.869 0.000501      -1.69 
##  9  10.8    67 fortis     11.6 -0.769 0.00335  0.870 0.000219      -0.885
## 10  10.3    68 fortis     11.8 -1.52  0.00255  0.869 0.000653      -1.75 
## # ℹ 1,424 more rows
augment(M3) %>% 
 ggplot(aes(wingl, .resid)) +
  geom_point(aes(color = species), alpha =0.4) +
  geom_hline(yintercept = 0, lty =2) +
  facet_wrap(~species, scales = "free_x") +
  labs(x = "Wing Length (mm)", y = "Beak height (mm)") +
  theme_bw()

Answer With the above fixed effects model we created, we estimated multiple parameters to account for observed differences among the species. However, this will consume multiple degrees of freedom. In addition, the model doesn’t generalize beyond the levels included in it. If, for example, we have another species with limited number, we can’t predict their outcome based on our model. Therefore, fixed effect models have inability to extrapolate beyond the observed values making them unreliable predictors for the general population.

Exercise 3

Question:Try to replicate as many figures above as you can. What do you notice about the intercepts? What do you notice about the slopes? How does this compare to the previous models we fit?

Plot 1:

M_random <-  lmer(beakh ~ wingl + (1 | species), data = finches)

finches$predict_lmer <- predict(M_random)

finches |> 
ggplot(aes(wingl, beakh, colour = species)) +
  geom_point(alpha = 0.1) + # alpha = 0.1 make 10% opaque
  geom_line(aes(y = predict_lmer))  +
  theme_bw() + 
  labs(title = "Random Intercept Model", x= "Wing Length(mm)", y="Beak Height(mm)", subtitle = "Intercepts are normally distributed")

Plot 2:

finches$predict_lmer_population <- 
  predict(M_random, re.form = NA)


finches |> 
ggplot(aes(wingl, beakh, colour = species)) +
  geom_point(alpha = 0.1) +
  geom_line(aes(y = predict_lmer)) +
  geom_line(aes(y = predict_lmer_population), 
            colour = "grey", 
            size = 1) +
  theme_bw() + 
  labs(title = "Random Intercept Model", x= "Wing Length(mm)", y="Beak Height(mm)", subtitle = "Intercepts are normally distributed")

ranef(M_random)
## $species
##              (Intercept)
## conirostris    1.3417493
## difficilis    -2.5605229
## fortis         0.4037595
## fuliginosa    -2.0911466
## magnirostris   5.3831675
## scandens      -2.4770068
## 
## with conditional variances for "species"
ranef(M_random)$species[, 1]
## [1]  1.3417493 -2.5605229  0.4037595 -2.0911466  5.3831675 -2.4770068
re <- ranef(M_random)$species %>% 
  mutate(species = row.names(.)) %>% 
  rename(intercept = `(Intercept)`) 
ggplot(re, aes(x = 1, y = intercept)) + geom_point(alpha = 0.7)

round(mean(ranef(M_random)$species[, 1]), 2)
## [1] 0

Answer The mean of the random intercepts is always zero. Because the assumption of random effects model is that the estimated effects are deviations from the grand intercept and they are normally distributed around this.

arm::display(M_random)
## lmer(formula = beakh ~ wingl + (1 | species), data = finches)
##             coef.est coef.se
## (Intercept) -3.82     1.38  
## wingl        0.22     0.01  
## 
## Error terms:
##  Groups   Name        Std.Dev.
##  species  (Intercept) 3.10    
##  Residual             0.90    
## ---
## number of obs: 1434, groups: species, 6
## AIC = 3838.8, DIC = 3819.5
## deviance = 3825.1
slope <- fixef(M_random)[[2]] %>% round(1)

Answer The single slope value is 0.2

Exercise 4

How might we make the intercept more meaningful if we were to refit this model? (Hint: consider centering your predictor variable!)

finches$beakh_ctr <- finches$beakh - mean(finches$beakh)
finches$wingl_ctr <- finches$wingl - mean(finches$wingl)
M_ctr <-lmer(beakh_ctr ~ wingl_ctr + (1 | species), data = finches)
arm::display(M_ctr)
## lmer(formula = beakh_ctr ~ wingl_ctr + (1 | species), data = finches)
##             coef.est coef.se
## (Intercept) 0.39     1.27   
## wingl_ctr   0.22     0.01   
## 
## Error terms:
##  Groups   Name        Std.Dev.
##  species  (Intercept) 3.10    
##  Residual             0.90    
## ---
## number of obs: 1434, groups: species, 6
## AIC = 3838.8, DIC = 3819.5
## deviance = 3825.1

*Answer

One approach in making the intercept more meaningful in a random effects model, is to center the predictor variable. It involves subtracting the mean of the predictor variable from each individual value, resulting in a new predictor variable with a mean of 0. This would yield a more interpretable intercept, representing the expected outcome when the centered predictor is at its mean value.We can also transform the outcome measure similarly.By centering the variables wing length and beak height we get a now intercept 0.39. We would expect a bird with a wing length of 1mm to have a beak height of 0.39 mm.