# load libraries
library(tidyverse)
library(data.table)
library(broom)
library(table1)
library(GGally)
library(marginaleffects)
library(modelsummary)
library(lmerTest)
library(faux)
Simulating data is an important step when analyzing data, as it serves a range of purposes. First, it helps clarify our assumptions and expectations regarding treatment effects we might realistically observe, the types of interactions we should consider, the size and features of the data we need to establish the claims we want to make. We can work in a “clean” environment where variables are truly normal, there are no missing values and data is “well behaved”. Once we grapple with an ideal world we can slowly add complexities and see how they change the picture.
Secondly, simulating “fake” data is a general method to understand how statistical methods work when repeatedly sampling data. By automating the sampling processes, we can evaluate the model’s performance. We can define the parameters in our “fake” population and compare the models estimations and predictions with those true values, and we can include features to challenge our assumptions and improve our understanding. We simulate in order to test and validate our models before applying them to real data.
Third, simulating fake data helps find issues in our code. If your model struggles to recover true parameters with large samples or low data variance, it could signal a coding or conceptual problem. Overlaying simulated data with assumed and fitted models can aid in identifying these issues.
Finally, simulating synthetic data is crucial when planning new studies or collecting data. It provides a basis for what to expect, ensuring a better understanding of potential outcomes.
obs_per_cluster <- 10
n_cluster <- 40
# Fixed intercept
alpha_0 <- 1
# Fixed slope
beta_0 <- .5
# Residuals st.dev (level 1)
sig <- 1
# Random intercept st.dev (level 2)
sig_u <- .5
# Random slope st.dev (level 2)
sig_v <- .25
# Independent random effects
cor <- 0
# Create a dataset that can be reproduced
set.seed(888)
# step 1: create the units
df <- add_random(
cluster = n_cluster, # first the clusters
obs = obs_per_cluster # second, the observations
)
# Print the result
# try to figure out what just happened
df |>
print(n = 15)
## # A tibble: 400 × 2
## cluster obs
## <chr> <chr>
## 1 cluster01 obs01
## 2 cluster01 obs02
## 3 cluster01 obs03
## 4 cluster01 obs04
## 5 cluster01 obs05
## 6 cluster01 obs06
## 7 cluster01 obs07
## 8 cluster01 obs08
## 9 cluster01 obs09
## 10 cluster01 obs10
## 11 cluster02 obs01
## 12 cluster02 obs02
## 13 cluster02 obs03
## 14 cluster02 obs04
## 15 cluster02 obs05
## # ℹ 385 more rows
# step 2: Add anything at level 2
# Here we have random intercept/slope
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
)
# Print the result
# try to figure out what just happened
df |>
print(n = 15)
## # A tibble: 400 × 6
## cluster obs u_i v_i a_i b_i
## <chr> <chr> <dbl> <dbl> <dbl> <dbl>
## 1 cluster01 obs01 0.976 -0.0495 1.98 0.450
## 2 cluster01 obs02 0.976 -0.0495 1.98 0.450
## 3 cluster01 obs03 0.976 -0.0495 1.98 0.450
## 4 cluster01 obs04 0.976 -0.0495 1.98 0.450
## 5 cluster01 obs05 0.976 -0.0495 1.98 0.450
## 6 cluster01 obs06 0.976 -0.0495 1.98 0.450
## 7 cluster01 obs07 0.976 -0.0495 1.98 0.450
## 8 cluster01 obs08 0.976 -0.0495 1.98 0.450
## 9 cluster01 obs09 0.976 -0.0495 1.98 0.450
## 10 cluster01 obs10 0.976 -0.0495 1.98 0.450
## 11 cluster02 obs01 0.772 -0.0307 1.77 0.469
## 12 cluster02 obs02 0.772 -0.0307 1.77 0.469
## 13 cluster02 obs03 0.772 -0.0307 1.77 0.469
## 14 cluster02 obs04 0.772 -0.0307 1.77 0.469
## 15 cluster02 obs05 0.772 -0.0307 1.77 0.469
## # ℹ 385 more rows
# step 3: add anything 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
)
# Print the result
# try to figure out what just happened
df |>
print(n = 20)
## # A tibble: 400 × 9
## cluster obs u_i v_i a_i b_i x epsilon y
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 cluster01 obs01 0.976 -0.0495 1.98 0.450 -0.667 1.13 2.81
## 2 cluster01 obs02 0.976 -0.0495 1.98 0.450 -1.83 0.162 1.31
## 3 cluster01 obs03 0.976 -0.0495 1.98 0.450 0.807 -1.92 0.421
## 4 cluster01 obs04 0.976 -0.0495 1.98 0.450 0.875 0.612 2.98
## 5 cluster01 obs05 0.976 -0.0495 1.98 0.450 -1.64 0.982 2.22
## 6 cluster01 obs06 0.976 -0.0495 1.98 0.450 1.47 -0.156 2.48
## 7 cluster01 obs07 0.976 -0.0495 1.98 0.450 0.864 -0.558 1.81
## 8 cluster01 obs08 0.976 -0.0495 1.98 0.450 0.750 -0.698 1.62
## 9 cluster01 obs09 0.976 -0.0495 1.98 0.450 0.263 0.201 2.30
## 10 cluster01 obs10 0.976 -0.0495 1.98 0.450 1.18 0.252 2.76
## 11 cluster02 obs01 0.772 -0.0307 1.77 0.469 0.767 -0.584 1.55
## 12 cluster02 obs02 0.772 -0.0307 1.77 0.469 0.897 1.20 3.39
## 13 cluster02 obs03 0.772 -0.0307 1.77 0.469 0.832 -1.46 0.705
## 14 cluster02 obs04 0.772 -0.0307 1.77 0.469 -1.72 1.18 2.14
## 15 cluster02 obs05 0.772 -0.0307 1.77 0.469 -0.615 -0.336 1.15
## 16 cluster02 obs06 0.772 -0.0307 1.77 0.469 0.0822 0.0150 1.83
## 17 cluster02 obs07 0.772 -0.0307 1.77 0.469 -1.39 0.0658 1.19
## 18 cluster02 obs08 0.772 -0.0307 1.77 0.469 -1.29 1.24 2.40
## 19 cluster02 obs09 0.772 -0.0307 1.77 0.469 1.23 -0.527 1.82
## 20 cluster02 obs10 0.772 -0.0307 1.77 0.469 -0.861 -0.376 0.992
## # ℹ 380 more rows
# For the models, we really only need
# the cluster id, the y and the x
df <- df |> select(cluster, x, y)
# Print the result
# try to figure out what just happened
df |>
print(n = 20)
## # A tibble: 400 × 3
## cluster x y
## <chr> <dbl> <dbl>
## 1 cluster01 -0.667 2.81
## 2 cluster01 -1.83 1.31
## 3 cluster01 0.807 0.421
## 4 cluster01 0.875 2.98
## 5 cluster01 -1.64 2.22
## 6 cluster01 1.47 2.48
## 7 cluster01 0.864 1.81
## 8 cluster01 0.750 1.62
## 9 cluster01 0.263 2.30
## 10 cluster01 1.18 2.76
## 11 cluster02 0.767 1.55
## 12 cluster02 0.897 3.39
## 13 cluster02 0.832 0.705
## 14 cluster02 -1.72 2.14
## 15 cluster02 -0.615 1.15
## 16 cluster02 0.0822 1.83
## 17 cluster02 -1.39 1.19
## 18 cluster02 -1.29 2.40
## 19 cluster02 1.23 1.82
## 20 cluster02 -0.861 0.992
## # ℹ 380 more rows
# Complete pooling
M_com_pooling <- lm(y~x,data=df)
## No pooling (without interaction)
M_no_pooling <- lm(y~x+cluster,data=df)
## No pooling (with interaction)
M_no_pooling_int <- lm(y~x*cluster,data=df)
## Partial pooling (random intercept, fixed slope)
M_part_pooling <- lmer(y~x+(1|cluster),data=df)
## Partial pooling (random intercept, random slope)
M_part_pooling_randSlope <- lmer(y~x+(x|cluster),data=df)
modelsummary(
list(
'Complete pooling' = M_com_pooling,
'No pooling' = M_no_pooling,
'No pooling + interaction' = M_no_pooling_int,
'Multilevel model' = M_part_pooling,
'Multilevel model + random slopes' = M_part_pooling_randSlope),
fmt = 2,
coef_omit = "clustercluster",
estimate = "{estimate} ({std.error}){stars}",
statistic = NULL,
stars = TRUE
)
| Complete pooling | No pooling | No pooling + interaction | Multilevel model | Multilevel model + random slopes | |
|---|---|---|---|---|---|
| (Intercept) | 0.94 (0.06)*** | 1.95 (0.31)*** | 2.05 (0.28)*** | 0.94 (0.11)*** | 0.97 (0.11)*** |
| x | 0.57 (0.06)*** | 0.58 (0.05)*** | 0.08 (0.25) | 0.57 (0.05)*** | 0.56 (0.08)*** |
| SD (Intercept cluster) | 0.61 | 0.61 | |||
| SD (x cluster) | 0.42 | ||||
| Cor (Intercept~x cluster) | -0.18 | ||||
| SD (Observations) | 0.97 | 0.88 | |||
| Num.Obs. | 400 | 400 | 400 | 400 | 400 |
| R2 | 0.197 | 0.476 | 0.616 | ||
| R2 Adj. | 0.195 | 0.417 | 0.521 | ||
| R2 Marg. | 0.198 | 0.188 | |||
| R2 Cond. | 0.423 | 0.520 | |||
| AIC | 1246.6 | 1153.8 | 1107.8 | 1189.4 | 1160.5 |
| BIC | 1258.6 | 1321.5 | 1431.1 | 1205.4 | 1184.5 |
| ICC | 0.3 | 0.4 | |||
| Log.Lik. | -620.303 | -534.910 | -472.916 | ||
| F | 97.463 | 8.148 | 6.486 | ||
| RMSE | 1.14 | 0.92 | 0.79 | 0.93 | 0.81 |
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.
Answer: The partial pooling model (random slope and intercept) has the lowest BIC, but the linear model including an interaction part and no pooling has the lowest AIC and RMSE.
Considering the model diagnostic it seems that the later model might be the better choice. But, considering the data structure, multilevel model with random intercept and slopes might be the best option.
Use your models to create a caterpillar plot for the intercepts and lattice 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?
random_effects <- ranef(M_part_pooling_randSlope)
random_effects_df <- as.data.frame(random_effects)
# Caterpillar plot
# Method 1
# the CI is a bit different between the two
ggplot(random_effects_df[random_effects_df$term=='(Intercept)',], aes(y = grp, x = condval)) +
geom_point(position = position_dodge(width = 0.5), size = 3) +
geom_errorbar(
aes(xmin = condval - 2*condsd, xmax = condval + 2*condsd),
position = position_dodge(width = 0.5),
width = 0.2
) +
labs(title = "Random Effects Caterpillar Plot (Intercepts)", x = "Cluster Intercepts", y = NULL) +
theme_minimal()
# Method 2
# predictions of y for each cluster at x = 0
# predict_y <- M_part_pooling_randSlope |>
# 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!
# predict_y |>
# ggplot(aes(xmin = lb, xmax = ub, y = cluster , x = estimate)) +
# geom_pointrange( ) +
# labs(x = "Estimate of the intercept (Y_hat when X=0)", y = NULL) +
# theme_minimal()
# Spaghetti plot for Random Intercept - Fixes Slope
predictions(M_part_pooling) |>
ggplot(aes(x=x,y=y,group=cluster,color = cluster)) +
geom_point() +
geom_line(aes(y = estimate)) +
theme_minimal()+
theme(legend.position='none')
# Lattice plot for Random Intercept - Fixes Slope
predictions(M_part_pooling) |>
ggplot(aes(x=x,y=y,group=cluster,color = cluster)) +
geom_point() +
geom_line(aes(y = estimate)) +
facet_wrap(~cluster) +
theme_minimal()+
theme(legend.position='none')
# Spaghetti plot for Random Intercept - Random Slope
predictions(M_part_pooling_randSlope) |>
ggplot(aes(x=x,y=y,group=cluster,color = cluster)) +
geom_point() +
geom_line(aes(y = estimate)) +
theme_minimal()+
theme(legend.position='none')
# Lattice plot for Random Intercept - Random Slope
predictions(M_part_pooling_randSlope) |>
ggplot(aes(x=x,y=y,group=cluster,color = cluster)) +
geom_point() +
geom_line(aes(y = estimate)) +
facet_wrap(~cluster) +
theme_minimal()+
theme(legend.position='none')
Describe and discuss the plots: what new light do they shed? What are the advantages or disadvantages of presenting the models using these plots?
Answer: The lattice plots show a positive correlation between x and y in all clusters. The slope is slightly steeper in some clusters than in other clusters, but not that much. Also, the intercepts of in the different clusters varies a little, but not that much. The caterpillar plot shows that cluster-slopes are (approx.) max 1 point smaller (= less steep) and max 1 point greater (= steeper) than the average slope (= approx. 2). Cluster-intercepts are (approx.) max 2 point smaller and max 2 points greater than the average intercept (= approx. 2). The advantage of the lattice models is that they are easily interpretable. However, you need very many plots to show all clusters, and to show multiple variables. Caterpillar plots are a little bit harder to interpret, but are better at summarizing a lot of information.
Our aim in examining this data is to estimate how radon levels are distributed across the approximately 3000 counties in the United States. This information can empower homeowners to decide whether to test and address radon in their homes, using the best local knowledge available.
To conduct this analysis, we view the data hierarchically: houses (level one) within counties (level 2). If we were to delve deeper into multiple measurements within houses, we could create a three-tier hierarchy: measurements (level 1), houses (level 2), and counties (level 3). During the analysis, we consider an important factor: where the measurement was taken, whether in the basement or on the first floor. Radon, originating underground, can more readily enter homes built into the ground.
Additionally, at the county level, we used a a measurement of soil uranium available for each county. This hierarchical model enables us to create a regression model for individual measurements while accommodating consistent, unexplained variations among the 3000 counties.
This section closely follows chapter 12 in Gellman and Hill’s influential book Data analysis using regression and multilevel/hierarchical models. You will find the chapter available as an optional reading (link also available through Brightspace). The chapter is available on Perusall to allow you to share code, discuss, or ask questions. I will be looking at the discussion from time to time, so if you need help, please do not hesitate to #tag me 🤙
In that chapter you will find the background for the study, and an explanation of the variables. The original dataset and the code used to produce the book is available here.
The dataset consists of a large number of measurements of the gas Radon, and so in this document we will be including only the measurements from the state of Minnesota. Feel free to choose a different state if you like.
# load dataset
# radon <- read_rds("https://bit.ly/BMLR-Radon")
# saveRDS(radon,file='radon.rds')
radon <- readRDS('radon.rds')
#
radon_mn <- read_rds("radon.rds") |>
filter(state == "MN") |>
# drop counties without measurements
mutate(county = fct_drop(county)) |>
mutate(first_floor = as.factor(first_floor ))
Create a table1 and use GGally::ggpairs to explore your data.
display4 <- c (323, 141, 8, 366) # subset of counties to display
radon_mn_4 <- radon_mn |>
filter(county_index %in% display4)|>
# drop counties without measurements
mutate(county = fct_drop(county))
label(radon_mn_4$radon) <- 'Radon level'
label(radon_mn_4$log.radon) <- 'Radon level (log scale)'
label(radon_mn_4$first_floor) <- 'Floor'
label(radon_mn_4$u) <- 'Soil uranium'
levels(radon_mn_4$first_floor) = list('Basement' =0, 'First floor'=1)
table1(~radon+ u|county+first_floor ,
radon_mn_4,
overall = F)
ANOKA |
HENNEPIN |
ST LOUIS |
WASHINGTON |
|||||
|---|---|---|---|---|---|---|---|---|
| Basement (N=49) |
First floor (N=3) |
Basement (N=94) |
First floor (N=11) |
Basement (N=100) |
First floor (N=16) |
Basement (N=41) |
First floor (N=5) |
|
| Radon level | ||||||||
| Mean (SD) | 3.08 (2.03) | 1.03 (0.802) | 4.84 (3.57) | 2.33 (2.02) | 3.27 (3.89) | 1.82 (1.71) | 5.13 (4.01) | 1.48 (0.653) |
| Median [Min, Max] | 2.40 [0.400, 8.10] | 1.10 [0.200, 1.80] | 4.00 [0.400, 23.6] | 2.10 [0.400, 7.60] | 2.15 [0.200, 32.2] | 1.35 [0.400, 7.20] | 4.30 [0.800, 20.4] | 1.20 [0.800, 2.50] |
| Soil uranium | ||||||||
| Mean (SD) | -0.847 (0) | -0.847 (0) | -0.0965 (0) | -0.0965 (0) | -0.475 (0) | -0.475 (0) | -0.147 (0) | -0.147 (0) |
| Median [Min, Max] | -0.847 [-0.847, -0.847] | -0.847 [-0.847, -0.847] | -0.0965 [-0.0965, -0.0965] | -0.0965 [-0.0965, -0.0965] | -0.475 [-0.475, -0.475] | -0.475 [-0.475, -0.475] | -0.147 [-0.147, -0.147] | -0.147 [-0.147, -0.147] |
plot_ggpairs <- ggpairs(radon_mn_4, columns = c(3,8,5),
columnLabels = c("County","Radon levels", "Soil uranium levels"),
legend = 1,
upper = list(continuous = "box", combo = "facethist", discrete = "barDiag"),
lower = list(continuous = "cor", combo = "facethist", discrete = "barDiag"),
diag = list(continuous = wrap("densityDiag", alpha=0.1), discrete = "densityDiag"),
mapping = aes(colour=radon_mn_4$county)
) +
labs(fill = "County")
plot_ggpairs + theme_minimal() + ggtitle('Radon and uranium levels in the state of Minessota') + theme(legend.position = "bottom")
You will now visualize the estimated and confidence interval for the average log Radon across different counties, against the (jittered) number of measurements taken in said county. We will use the estimation to compare between two models: the no pooling model and the multilevel model with partial pooling, both without predictors. The horizontal line in each plot represents an estimate of the average radon level across all counties. This is a replication of figure 12.1 in the above mentioned chapter.
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.
radon_mn_count <- radon_mn |>
count(county, name = "n.obs")
m.no_pool <- lm(log.radon ~ 0 + county, data = radon_mn)
m.partial_pool <- lmer(log.radon ~ (1|county), data = radon_mn)
# Use here the two models - first the fixed effects (no pooling)
# model, and then the multilevel (partial pooling) model.
plot1 <- m.no_pool |>
predictions(newdata = datagrid(county = unique)) |>
as_tibble() |> inner_join(radon_mn_count, by = "county") |>
select(county, estimate, conf.low, conf.high, n.obs) |>
ggplot(
aes(
x = n.obs,
y = estimate ,
ymin = conf.low ,
ymax = conf.high
)
) +
scale_x_continuous(breaks = c(1,2,4,6,8,10,20,40,60,80,100,140),trans = scales::log_trans()) +
geom_pointrange(
position = position_jitter(width = .5, height = 0)
) +
geom_hline(yintercept = mean(predictions(m.no_pool)$estimate),size=1)+
xlab('') + ylab('')+ggtitle('No pooling (fixed effects)')+
theme_minimal()
## 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.
plot2 <- m.partial_pool |>
predictions(newdata = datagrid(county = unique)) |>
as_tibble() |> inner_join(radon_mn_count, by = "county") |>
select(county, estimate, conf.low, conf.high, n.obs) |>
ggplot(
aes(
x = n.obs,
y = estimate ,
ymin = conf.low ,
ymax = conf.high
)
) +
scale_x_continuous(breaks = c(1,2,4,6,8,10,20,40,60,80,100,140),trans = scales::log_trans()) +
geom_pointrange(
position = position_jitter(width = .5, height = 0)
) +
geom_hline(yintercept = mean(predictions(m.partial_pool)$estimate),size=1)+
xlab('') + ylab('')+ggtitle('Partial pooling (multi-level model)')+
theme_minimal()
plot3 <- gridExtra::arrangeGrob(plot1,plot2,left = 'Estimated log(radon) in the county',bottom = 'Number of obsevations')
plot(plot3)
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.
Answer: Countries with fewer measurements have more variable estimates and larger standard errors because averages are based smaller sample size / less information. The main advantage of no-pooling analysis compared with the multilevel model is that is is easy and understandable. The main disadvantage of no-pooling analysis is that is overestimates variation between counties, ie it overfits the data within each county and tends to make the indivudal counties look more different than they actually are.
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?
# Fit the model (you will need to fit all three models)
# complete pooling
mdl_1 <- lm(log.radon ~ first_floor , data = radon_mn)
# no pooling
mdl_2 <- lm(log.radon ~ first_floor * county , data = radon_mn)
# partial pooling
mdl_3 <- lmer(log.radon ~ first_floor + (first_floor|county), data = radon_mn)
# select some counties
selected_counties <- c("BLUE EARTH" , "CLAY" , "DAKOTA" , "DOUGLAS",
"KOOCHICHING" , "LAC QUI PARLE" , "MCLEOD" , "MILLE LACS",
"MOWER" , "OTTER TAIL" , "RAMSEY" , "REDWOOD",
"RICE" , "SCOTT" , "ST LOUIS" , "STEARNS")
# Collect the predictions
pred1 <- mdl_1 |>
predictions(
newdata = datagrid(
first_floor = c(0, 1),
county = selected_counties
)
) |>
select(county, first_floor, estimate, conf.low, conf.high) |>
as_tibble( )
## Warning: Some of the variable names are missing from the model data: county
pred2 <- mdl_2 |>
predictions(
newdata = datagrid(
first_floor = c(0, 1),
county = selected_counties
)
) |>
select(county, first_floor, estimate, conf.low, conf.high) |>
as_tibble( )
## Warning: Model matrix is rank deficient. Some variance-covariance parameters are
## missing.
pred3 <- mdl_3 |>
predictions(
newdata = datagrid(
first_floor = c(0, 1),
county = selected_counties
)
) |>
select(county, first_floor, estimate, conf.low, conf.high) |>
as_tibble( )
radon_mn |>
filter(county %in% selected_counties) |>
ggplot(aes(x = first_floor, y = log.radon)) +
geom_point() +
geom_line(data = pred1, aes(first_floor, estimate,group=county),linetype='dashed',color='red', linewidth=1) +
geom_line(data = pred2, aes(first_floor, estimate,group=county), linewidth=1) +
geom_line(data = pred3, aes(first_floor, estimate,group=county),linetype='dashed',color='blue', linewidth=1) +
facet_wrap(~county) +
theme_bw() +
xlab('')+
ylab('Log Radon level')
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?
Answer: The graphs show the observed and predicted level of log(radon) per county for houses at the ground floor and houses at the first floor. In the original plot, red line are predictions based on complete pooling, black line is based on the model without pooling, and the blue line is based on the partial pooling model. In the plot with a twist, full line are predictions based on complete pooling, dashed line is based on the model without pooling, and the dotted line is based on the partial pooling model. Most of the time, levels of log(radon) seem lower at the first floor compared with the ground floor. In counties with only few observations, the predictions based on the no pooling method seem to differ more from the partial or complete pooling method. In general, in counties with more observations, all lines are more similar. In two states (BIG STONE and SHERBURNE) there were no observations on the first floor.
Finally, we 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)
# The multilevel model for the radon as a function of level-2 uranium
md.lvl12 <- lmer(log.radon ~ u + (1|county), data = radon_mn)
# Predictions for the linear model
pred.lm <- predictions(
md.lm,
)
# predictions for the multilevel model
# stratified by the level of uranium
pred.lvl12 <- predictions(
md.lvl12,
by = "u"
)
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),
linetype='dashed',
size=.5
) +
geom_ribbon(data = pred.lm, aes(ymin=conf.low,
ymax=conf.high),
linetype=2,
alpha=0.1)+
theme_minimal() +
xlab('Uranium (county level)')+
ylab('County level coefficinets')
After replicating this graph, please explain it briefly.
Answer: County level coefficients are quite similar to each other when estimated by the models. the confidence interval in middle levels of Uranium is lower in both models.
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.
observation.count<- 20
county.count <- 10
# Fixed intercept
alpha_0 <- 1
# Fixed slope first_floor
beta_0 <- -0.5
# Fixed slope uranium
gamma_0 <- 0.75
# Residuals st.dev (level 1)
sig <- 1
# Random intercept st.dev (level 2)
sig_u <- 0.5
# Random slope st.dev (level 2)
sig_v <- 0.25
# Independent random effects
cor <- 0
set.seed(123)
# step 1: create the units
radon_sim <- add_random(
county = county.count, # first the clusters
obs = observation.count # second, the observations
)
# step 2: Add anything at level 2
# Random intercept, fixed slope
radon_sim <- radon_sim |>
add_ranef(
"county",
u_i = sig_u,
.cors = cor
) |> mutate(
a_i = alpha_0 + u_i,
b_i = beta_0,
g_i = gamma_0
)
# step 3: add anything at level 1
radon_sim <- radon_sim |>
mutate(
first_floor = rbinom(county.count * observation.count, 1, 0.5),
u = rep(rnorm(county.count, 0, sig_u), each=observation.count),
epsilon = rnorm(county.count * observation.count, 0, sig),
y = a_i + b_i * first_floor + g_i * u + epsilon
) |>
mutate(first_floor=factor(first_floor))
# Filter the data
radon_sim <- radon_sim |> dplyr::select(county, obs, y, first_floor, u)
# Print the result
radon_sim |>
print(n = 20)
## # A tibble: 200 × 5
## county obs y first_floor u
## <chr> <chr> <dbl> <fct> <dbl>
## 1 county01 obs01 0.122 1 -0.288
## 2 county01 obs02 -0.943 1 -0.288
## 3 county01 obs03 -0.487 1 -0.288
## 4 county01 obs04 -0.252 1 -0.288
## 5 county01 obs05 1.85 1 -0.288
## 6 county01 obs06 -0.648 1 -0.288
## 7 county01 obs07 0.239 1 -0.288
## 8 county01 obs08 0.0820 1 -0.288
## 9 county01 obs09 -0.458 0 -0.288
## 10 county01 obs10 0.433 0 -0.288
## 11 county01 obs11 1.45 1 -0.288
## 12 county01 obs12 0.456 1 -0.288
## 13 county01 obs13 0.0452 1 -0.288
## 14 county01 obs14 -0.418 1 -0.288
## 15 county01 obs15 -1.55 0 -0.288
## 16 county01 obs16 1.64 0 -0.288
## 17 county01 obs17 -1.46 1 -0.288
## 18 county01 obs18 1.24 0 -0.288
## 19 county01 obs19 2.41 0 -0.288
## 20 county01 obs20 -0.940 0 -0.288
## # ℹ 180 more rows
######
## model with no pooling
model_simData_no_pool <- lm(y ~ first_floor + u, data=radon_sim)
## model with no pooling + interaction
model_simData_no_pool_int <- lm(y ~ first_floor * u, data=radon_sim)
## model with partial pooling, random intercept, fixed slope, floor and uranium as predictors in SIMULATED DATA
model_simData_pool <- lmer(y ~ first_floor + u + (1 | county), data=radon_sim)
# Collect the predictions
pred1 <- model_simData_no_pool |>
predictions()
#
pred2 <- model_simData_no_pool_int |>
predictions()
#
pred3 <- model_simData_pool |>
predictions()
pred2$county <- pred3$county
pred1$county <- pred3$county
radon_sim |>
ggplot(aes(x = first_floor, y = y)) +
geom_point() +
geom_line(data = pred1, aes(first_floor, estimate,group=county),linetype='dashed',color='red', linewidth=1) +
geom_line(data = pred2, aes(first_floor, estimate,group=county), linewidth=1) +
geom_line(data = pred3, aes(first_floor, estimate,group=county),linetype='dashed',color='blue', linewidth=1) +
facet_wrap(~county) +
theme_bw() +
xlab('')+
ylab('Simulated data')
Answer: when using the previous model parameters, predicted dataset was fairly similar to the original dataset. Paramater estimates from the partial and complete pooling model are very similar in the simulated and real data. Estimates from the no pooling model are quite different.