Exercise 1: simulate your clustered data

#Adjust the parameters, simulate your clustered data and present the results of the three types of models using the modelsummary package. Interpret your models and compare the estimations with each other, and with the six parameters used to simulate your data. Is there one single model that is superior to all the rest in terms of estimating the parameters? If so which is it, and what makes it better? If not, Which model works best for what purpose? In your answer, please pay attention to the standard errors and the Intraclass Correlation Coefficient (ICC) of your multilevel model(s). What does the ICC mean? How much does it deviate from what you would expect? For more about the ICC, please see below.

#Setting parameters
obs_per_cluster <-  8
n_cluster <-  10
alpha_0 <-  1  
beta_0 <- .5 
sig  <-  1
sig_u <-  .5
sig_v <-  .25
cor <-  0
set.seed(888) 

 

 

 

#Creating dataset
df <- add_random(
    cluster = n_cluster,  # first the clusters
    obs = obs_per_cluster # second, the observations
    ) 

 

 

 

#Adding Random Effects at Level 2
df <- df %>%
  add_ranef(
    "cluster",
    u_i = sig_u,
    v_i = sig_v,
    .cors = cor
    ) |> mutate(
      a_i = alpha_0 + u_i, 
      b_i = beta_0  + v_i
    )

 

 

 

#Adding Random Effects at Level 1
df <- df %>%
  mutate(
    x       = rnorm(n_cluster * obs_per_cluster),
    epsilon = rnorm(n_cluster * obs_per_cluster, 0, sig),
    y = a_i + b_i * x + epsilon
    )

 

 

 

#Selecting values
df  <- df %>% dplyr::select(cluster, x, y)

 

 

 

#Creating models
M_complete_pooling <- lm(y ~ x, data = df)
M_no_pooling <- lm(y ~ x + factor(cluster), data = df)
M_no_pooling_interaction <- lm(y ~ x*factor(cluster), data = df)
M_partial_pooling <- lmer(y ~ x + factor(cluster) + (1 | cluster), data = df)
## Warning in as_lmerModLT(model, devfun): Model may not have converged with 1
## eigenvalue close to zero: -1.3e-21
M_partial_pooling_slope <- lmer(y ~ x + factor(cluster) + (1 + x | cluster), data = df)
## Warning in checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv, :
## unable to evaluate scaled gradient
## Warning in checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv, :
## Hessian is numerically singular: parameters are not uniquely determined
## Warning in as_lmerModLT(model, devfun): Model may not have converged with 1
## eigenvalue close to zero: -3.2e-09
models <- list(
  "Complete Pooling" = M_complete_pooling,
  "No Pooling" = M_no_pooling,
  "No Pooling + Interaction" = M_no_pooling_interaction,
  "Partial Pooling" = M_partial_pooling,
  "Partial Pooling + Random Slope" = M_partial_pooling_slope
  )

 

 

 

model_summary <- modelsummary(models, stars = TRUE)

Further explanation and exploration: The R2 is highest with the No pooling + interaction, however, this model is probably not as good as estimating observations. We don’t think there is a superior model base on the information in the table.

Exercise 2:

Use your models to create a caterpillar plot for the intercepts and lattice and/or spaghetti plots to show the features of your multilevel models. Describe and discuss the plots: what new light do they shed? What are the advantages or disadvantages of presenting the models using these plots?

# Exercise 2

 

# First, we need the list of clusters
clusters <- df %>% 
  pull(cluster) %>%  
  unique()

 

 

 

# Now let's fit our multilevel model
mdl_multilevel <- lmer(y ~ x + (x | cluster), df) 
## boundary (singular) fit: see help('isSingular')
# predictions of y for each cluster at x = 0
predict_y <- mdl_multilevel %>%  
  ranef() %>%  
  # Used the broom.mixed::augment function 
  # to calculate the confidence intervals
  augment() %>%  
  # convert to a tibble
  as_tibble() %>%  
  # Include only the random intercept
  filter(variable == "(Intercept)") %>%  
  # Now we order the results by ascending estimates
  arrange(estimate) %>%  
  mutate(cluster = fct_inorder(level)) 

 

 

 

# Finally, let's plot our caterpillar!
ggplot(predict_y, aes(xmin = lb, xmax = ub, y = cluster, x = estimate)) +
  geom_pointrange() +
  labs(x = "Estimate of the intercept (Y_hat when X=0)", y = NULL)

Discussion: Caterpillar Plot for Random Intercepts:

#Advantages: Caterpillar plots provide a clear visual representation of the variation in random intercepts across clusters. They make it easy to identify clusters with extreme intercept values. #Disadvantages: Caterpillar plots may become crowded if there are many clusters. They focus solely on intercepts and may not capture the entire random effects structure.

#Spaghetti Plot for Multilevel Model:

#Advantages: Spaghetti plots visualize the individual trajectories of clusters, showing how the outcome variable changes within each cluster. They are particularly useful for understanding the variability in slopes across clusters. #Disadvantages: Spaghetti plots can be complex if there are many clusters or if trajectories overlap. They may not be suitable for large datasets.

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

#Creation dataset
radon_mn <- read_rds("https://bit.ly/BMLR-Radon") |>
  filter(state == "MN") |>
  mutate(county = fct_drop(county))

 

 

 

#Creation GGpairs
columns_to_include <- c(2,4,8)
ggpairs(data=radon_mn,
        mapping = aes(color = factor(first_floor, labels = c("Not first floor", "First floor")), alpha = 0.5),
        columns = columns_to_include,
        cardinality_threshold = 85,
        progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#Create Table1

 

table1(~ radon + log.radon + fullfips + u |first_floor, overall = FALSE, caption = "Table 1: demographic characteristics stratified by whether measurement was taken on first floor or not", data = radon_mn)
## Warning in table1.formula(~radon + log.radon + fullfips + u | first_floor, :
## Terms to the right of '|' in formula 'x' define table columns and are expected
## to be factors with meaningful labels.
Table 1: demographic characteristics stratified by whether measurement was taken on first floor or not
0
(N=766)
1
(N=153)
radon
Mean (SD) 5.07 (4.54) 3.28 (3.83)
Median [Min, Max] 3.90 [0.100, 48.2] 2.10 [0, 25.4]
log.radon
Mean (SD) 1.33 (0.783) 0.713 (0.999)
Median [Min, Max] 1.36 [-2.30, 3.88] 0.742 [-2.30, 3.23]
fullfips
Mean (SD) 27100 (52.4) 27100 (50.8)
Median [Min, Max] 27100 [27000, 27200] 27100 [27000, 27200]
u
Mean (SD) -0.139 (0.366) -0.0970 (0.360)
Median [Min, Max] -0.0965 [-0.882, 0.528] -0.0900 [-0.882, 0.504]

Exercise 4: Replicate the figures below and explain why the counties with fewer measurements have more variable estimates and larger higher standard errors. What is the main advantage and disadvantage of no-pooling analysis, as illustrated in the plot on the left compared with the multilevel model? Explain.

# Creating models
radon_mn <- radon_mn %>%
  group_by(county) %>%
  mutate(num_observations = n()) %>%
  ungroup()
M_MN_no_pooling <- lm(log.radon ~ 0 + county, data = radon_mn)
M_MN_partial_pooling <- lmer(log.radon ~ (1 | county), data = radon_mn)

 

 

 

# Figure with no pooling
# Extract coefficients and calculate standard errors
county_names <- as.list(summary(M_MN_no_pooling)$coef[, 1])
observations_per_county <- table(radon_mn$county)
model_coefs <- summary(M_MN_no_pooling)$coef[, "Estimate"]
model_se <- summary(M_MN_no_pooling)$coef[, "Std. Error"]

 

 

 

data_plot <- data.frame(
  county = county_names,
  observations = as.numeric(table(radon_mn$county)),
  mean_log_radon = model_coefs,
  se_log_radon = model_se)

 

 

 

# Calculate the overall mean of log.radon
overall_mean_log_radon <- mean(radon_mn$log.radon)

 

 

 

# Create the plot
ggplot(data_plot, aes(x = observations, y = mean_log_radon)) +
  geom_errorbar(
    aes(ymin = mean_log_radon - se_log_radon, ymax = mean_log_radon + se_log_radon),
    position = position_dodge(width = 0.9), width = 0.25, color = "black"
  ) +
  geom_point(position = position_dodge(width = 0.9), color = "red", size = 3) +
  geom_hline(yintercept = overall_mean_log_radon, color = "black", linetype = "solid", size = 1) +
  labs(
    x = "Number of Observations",
    y = "Mean log.radon (with SE)",
    title = "Mean log.radon by Number of Observations per County (No Pooling)"
  ) +
  theme_minimal() +
  scale_x_continuous(
    trans = "log",
    breaks = seq(min(data_plot$observations), max(data_plot$observations), by = 10))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: `position_dodge()` requires non-overlapping x intervals
## `position_dodge()` requires non-overlapping x intervals

# Figure with partial pooling
model_coefs_fixed <- fixef(M_MN_partial_pooling)
model_se_fixed <- se.fixef(M_MN_partial_pooling)

 

 

 

# Extract random effects and standard errors
random_effects <- ranef(M_MN_partial_pooling)$county[, "(Intercept)"]
random_effects_se <- se.ranef(M_MN_partial_pooling)$county[, "(Intercept)"]

 

 

 

# Calculate coefficients and standard errors including random effects
model_coefs <- model_coefs_fixed + random_effects
model_se <- random_effects_se

 

 

 

# Create the dataframe for plotting
data_plot <- data.frame(
  observations = as.numeric(table(radon_mn$county)),
  mean_log_radon = model_coefs,
  se_log_radon = model_se
)

 

 

 

# Calculate the overall mean of log.radon
overall_mean_log_radon <- mean(radon_mn$log.radon)

 

 

 

# Create the plot
ggplot(data_plot, aes(x = observations, y = mean_log_radon)) +
  geom_errorbar(
    aes(ymin = mean_log_radon - se_log_radon, ymax = mean_log_radon + se_log_radon),
    position = position_dodge(width = 0.9),
    width = 0.25,
    color = "black"
  ) +
  geom_point(
    aes(y = mean_log_radon),
    position = position_dodge(width = 0.9),
    color = "red",
    size = 3
  ) +
  geom_hline(
    yintercept = overall_mean_log_radon,
    color = "black",
    linetype = "solid",
    size = 1
  ) +
  labs(
    x = "Number of Observations",
    y = "Mean log.radon (with SE)",
    title = "Mean log.radon by Number of Observations per County (Partial Pooling)"
  ) +
  theme_minimal() +
  scale_x_continuous(
    trans = "log",
    breaks = seq(min(data_plot$observations), max(data_plot$observations), by = 10))
## Warning: `position_dodge()` requires non-overlapping x intervals
## `position_dodge()` requires non-overlapping x intervals

The main advantage and disadvantage of no-pooling analysis: The variability of the counties with fewer measurement is larger since they have less observations and thus more uncertainty. The no-pooling analysis is more flexible and allows us to see unique characteristics of each county without assuming a common structure. The strength of the partial-pooling model is that is gains strength from the whole population and projects it on each county.

Exercise 5: In this exercise, you will replicate a set of models as shown below. This illustration is based on the ideas shown in figure 12.4 in the book. Please replicate this illustration with a twist: for example, you may choose a different set of counties than the one shown below or the one shown in the book, or you may try something different. Please explain the graphs. What do the dashed red and black lines show? What is the blue line? What determines whether the blue line would be more similar to the red line or the black line? How is this figure compare to the one shown in chapter 12 of the book?

# Define counties to use
used_counties <- c("BLUE EARTH", "CLAY", "DAKOTA", "DOUGLAS", "RICE", "SCOTT", "REDWOOD", "MILLE LACS", "KOOCHICHING")

 

 

 

# Fit the model (multilevel)
mdl_multilevel <- lmer(log.radon ~ first_floor + (first_floor|county), data = radon_mn)

 

 

 

# Collect the predictions (multilevel)
pred_multi <- predictions(
                    mdl_multilevel,                
                    newdata = datagrid(
                    first_floor = c(0, 1),
                    county = used_counties))
pred_multi <- as_tibble(pred_multi)
pred_multi %>% dplyr::select(county, first_floor, estimate, conf.low, conf.high)
## # A tibble: 18 × 5
##    county      first_floor estimate conf.low conf.high
##    <fct>             <dbl>    <dbl>    <dbl>     <dbl>
##  1 BLUE EARTH            0    1.82     1.71      1.92 
##  2 CLAY                  0    1.89     1.78      2.00 
##  3 DAKOTA                0    1.35     1.25      1.46 
##  4 DOUGLAS               0    1.63     1.52      1.74 
##  5 KOOCHICHING           0    1.00     0.897     1.11 
##  6 MILLE LACS            0    1.37     1.26      1.48 
##  7 REDWOOD               0    1.64     1.53      1.74 
##  8 RICE                  0    1.74     1.64      1.85 
##  9 SCOTT                 0    1.61     1.50      1.71 
## 10 BLUE EARTH            1    1.34     1.18      1.51 
## 11 CLAY                  1    1.04     0.874     1.20 
## 12 DAKOTA                1    0.584    0.420     0.748
## 13 DOUGLAS               1    0.959    0.795     1.12 
## 14 KOOCHICHING           1    0.484    0.320     0.648
## 15 MILLE LACS            1    0.496    0.333     0.660
## 16 REDWOOD               1    1.24     1.07      1.40 
## 17 RICE                  1    0.953    0.789     1.12 
## 18 SCOTT                 1    1.21     1.05      1.37
# Fit the model (no-pooling)
mdl_no_pooling <- lm(log.radon ~ first_floor * county, data = radon_mn)

 

 

 

# Collect the predictions (no-pooling)
pred__no_pooling <- predictions(
                    mdl_no_pooling,                
                    newdata = datagrid(
                    first_floor = c(0, 1),
                    county = used_counties))
## Warning: Model matrix is rank deficient. Some variance-covariance parameters are
##   missing.
pred__no_pooling <- as_tibble(pred__no_pooling)
pred__no_pooling %>% dplyr::select(county, first_floor, estimate, conf.low, conf.high)
## # A tibble: 18 × 5
##    county      first_floor estimate conf.low conf.high
##    <fct>             <dbl>    <dbl>    <dbl>     <dbl>
##  1 BLUE EARTH            0    1.86     1.44      2.28 
##  2 CLAY                  0    2.10     1.63      2.56 
##  3 DAKOTA                0    1.35     1.16      1.54 
##  4 DOUGLAS               0    1.70     1.18      2.21 
##  5 KOOCHICHING           0    0.289   -0.556     1.13 
##  6 MILLE LACS            0    1.74     0.277     3.20 
##  7 REDWOOD               0    1.54     0.809     2.27 
##  8 RICE                  0    1.87     1.41      2.34 
##  9 SCOTT                 0    1.55     1.06      2.04 
## 10 BLUE EARTH            1    2.21     1.17      3.24 
## 11 CLAY                  1    0.999    0.267     1.73 
## 12 DAKOTA                1    0.418   -0.313     1.15 
## 13 DOUGLAS               1    1.31    -0.155     2.77 
## 14 KOOCHICHING           1    0.496   -0.235     1.23 
## 15 MILLE LACS            1   -0.693   -2.16      0.770
## 16 REDWOOD               1    3.03     1.57      4.49 
## 17 RICE                  1    0.875   -0.588     2.34 
## 18 SCOTT                 1    1.65     0.919     2.38
# Fit the model (complete-pooling)
mdl_complete_pooling <- lm(log.radon ~ first_floor, data = radon_mn)

 

 

 

# Collect the predictions (complete-pooling)
pred_complete <- predictions(
                    mdl_complete_pooling,                
                    newdata = datagrid(
                    first_floor = c(0, 1),
                    county = used_counties))
## Warning: Some of the variable names are missing from the model data: county
pred_complete <- as_tibble(pred_complete)
pred_complete %>% dplyr::select(county, first_floor, estimate, conf.low, conf.high)
## # A tibble: 18 × 5
##    county      first_floor estimate conf.low conf.high
##    <chr>             <dbl>    <dbl>    <dbl>     <dbl>
##  1 BLUE EARTH            0    1.33     1.27      1.38 
##  2 CLAY                  0    1.33     1.27      1.38 
##  3 DAKOTA                0    1.33     1.27      1.38 
##  4 DOUGLAS               0    1.33     1.27      1.38 
##  5 KOOCHICHING           0    1.33     1.27      1.38 
##  6 MILLE LACS            0    1.33     1.27      1.38 
##  7 REDWOOD               0    1.33     1.27      1.38 
##  8 RICE                  0    1.33     1.27      1.38 
##  9 SCOTT                 0    1.33     1.27      1.38 
## 10 BLUE EARTH            1    0.713    0.583     0.844
## 11 CLAY                  1    0.713    0.583     0.844
## 12 DAKOTA                1    0.713    0.583     0.844
## 13 DOUGLAS               1    0.713    0.583     0.844
## 14 KOOCHICHING           1    0.713    0.583     0.844
## 15 MILLE LACS            1    0.713    0.583     0.844
## 16 REDWOOD               1    0.713    0.583     0.844
## 17 RICE                  1    0.713    0.583     0.844
## 18 SCOTT                 1    0.713    0.583     0.844
radon_mn %>%
  filter(county %in% used_counties) %>%
  ggplot(aes(x = first_floor, y = log.radon)) +
  geom_point() +
  geom_line(data = pred_multi, aes(first_floor, estimate), color = "blue") +
  geom_line(data = pred__no_pooling, aes(first_floor, estimate), color = "black") +
  geom_line(data = pred_complete, aes(first_floor, estimate), color = "red") +
  facet_wrap(~county)

What do the dashed red and black lines show? Red is complete pooling, blue is multi-level pooling and black is no pooling. Red one is all the same, black line goes from mean to mean. What determines whether the blue (multilevel) line would be more similar to the red (complete pooling) line or the black line? We think the lines are more alike if the data is more homogeneous.The blue line would be closer to the red line if the effect of first_floor in that county would be closer to the overall effect of first_floor in the entire state.

Exercise 6 In this exercise you are going to add a fixed effect at the county level (level 2). This illustration is based on figure 12.6 in the book, and it shows the estimated county level coefficients, plotted vs. county level uranium levels, along with estimated multilevel regression line at level 2. After replicating this graph, please explain it briefly.

# The simple linear model for the general relationship between 
# Radon measurements and county level uranium
md.lm <- lm(log.radon ~ u , data = radon_mn)
pred.lm <- predictions(
  md.lm,
  )

 

 

 

# The multilevel model for the radon as a function of level-2 uranium
md.lvl12 <- lmer(log.radon ~ u +  (1|county), data = radon_mn)
pred.lvl12 <- predictions(
  md.lvl12,
  by = "u"
)

 

 

 

# Creating figure
pred.lvl12 %>%
  ggplot(aes(x = u, xend = u, y = conf.low, yend = conf.high)) +
  geom_segment() +
  geom_point(aes(y = estimate)) +
  geom_line(data = pred.lm, aes(x = u, y = estimate), color = "red") + 
  geom_ribbon(data = pred.lm, aes(ymin = conf.low, ymax = conf.high), fill = "pink", alpha = 0.5) +
  labs(
    x = "Uranium",
    y = "Mean log.radon",
    title = "Mean log. radon vs. Uranium"
  ) +
  theme_minimal()

The higher the amount of uranium, the higher the mean.log of radon in that county.

Exercise 7: Using the simulation techniques in questions 1 and 2, generate a synthetic dataset that would be similar to the radon data, in the sense that if you fitted the three models to your simulated dataset, you would get similar parameter estimations to the ones you got when fitting your models to the real Radon dataset. Explore your synthetic data using similar visualisations, and comment on similarities or differences between the Radon dataset and your simulated dataset.

# Creating dataframe
obs_per_county <-  5
n_county <-  20
alpha_0 <-  1.32674  
beta_0 <- 0.75203
sig  <-  0.8083
sig_u <-  0.3086
sig_v <-  0.4215
cor <-  -0.26
set.seed(7892) 

 

 

 

#Creating dataset
random_data <- add_random(
    county = n_county,  # first the clusters
    obs = obs_per_county # second, the observations
    ) 

 

 

 

#Adding Random Effects at Level 2
random_data <- random_data %>%
  add_ranef(
    "county",
    u_i = sig_u,
    v_i = sig_v,
    .cors = cor
    ) |> mutate(
      a_i = alpha_0 + u_i, 
      b_i = beta_0  + v_i
    )

 

 

 

#Adding Random Effects at Level 1
random_data <- random_data %>%
  mutate(
    u  = rnorm(n_county * obs_per_county),
    epsilon    = rnorm(n_county * obs_per_county, 0, sig),
    log.radon = a_i + b_i * u + epsilon
    )

 

 

 

#Selecting values
radon_complete_pooling <- lm(log.radon ~ u, data = radon_mn)
random_complete_pooling <- lm(log.radon ~ u, data = random_data)
radon_no_pooling <- lm(log.radon ~ u * county, data = radon_mn)
random_no_pooling <- lm(log.radon ~ u * county, data = random_data)
radon_multilevel <- lmer(log.radon ~ u + (u|county), data = radon_mn)
## boundary (singular) fit: see help('isSingular')
## Warning: Model failed to converge with 1 negative eigenvalue: -3.7e+01
random_multilevel <- lmer(log.radon ~ u + (u|county), data = random_data)

 

 


 

 

 

models <- list(
  "Complete Pooling Radon" = radon_complete_pooling,
  "Complete Pooling Random" = random_complete_pooling,
  "No Pooling Radon" = radon_no_pooling,
  "No Pooling Random" = random_no_pooling,
  "Multilevel Radon" = radon_multilevel,
  "Multilevel Random" = random_multilevel)

 

 

 

model_summary <- modelsummary(models, stars = TRUE)


 

pred.lm.random <- predictions(random_complete_pooling)

 

 

 

random_data$county <- as.factor(random_data$county)
md.lm.random <- lmer(log.radon ~ u + (1|county), data = random_data)
pred.lmer.random <- predictions(md.lm.random, by = 'u')

 

 

 

# Creating figure
pred.lmer.random %>%
  ggplot(aes(x = u, xend = u, y = conf.low, yend = conf.high)) +
  geom_segment() +
  geom_point(aes(y = estimate)) +
  geom_line(data = pred.lm.random, aes(x = u, y = estimate), color = "red") + 
  geom_ribbon(data = pred.lm.random, aes(ymin = conf.low, ymax = conf.high), fill = "pink", alpha = 0.5) +
  labs(
    x = "Uranium",
    y = "Mean log.radon",
    title = "Mean log. radon vs. Uranium"
  ) +
  theme_minimal()

Our data is normally distributed as opposed to the original Radon dataset. Especially in the amount of Uranium per county. Moreover, there are some counties below 0 mean.log Radon, which should not be possible. There is also a large difference between the number of observations in our synthetic database.