Radon, a natural radioactive gas, is a known carcinogen that can cause lung cancer, especially in high concentrations. In the United States, it’s estimated to lead to thousands of lung cancer deaths annually. Radon levels in homes across the country vary significantly, with some houses having dangerously high concentrations.

To pinpoint areas with high radon exposure, the Environmental Protection Agency conducted radon measurements in over 80,000 randomly selected houses nationwide. Our objective in analyzing this data was to estimate the range of radon levels in each of the approximately 3000 U.S. counties. This information would help homeowners decide whether to measure or reduce radon in their houses based on local conditions.

For the analysis, we organized the data hierarchically: houses within counties. If we were to consider multiple measurements within houses, it would create a three-level hierarchy of measurements, houses, and counties.


Creating a reproducible lab report

This time, you will need to use your own RStudio environment. You can also use one of the spaces you used for a previous lab, if you like!

Load the tidyverse, table1, GGally, broom, broom.mixed, lmerTest, faux, marginaleffects and the modelsummary packages, and any other packages you might deem useful. Load the radon.rds data set into your workspace, and assign it into an object called finches.

radon <- read_rds(“https://bit.ly/BMLR-Radon”)

Knit your file to see that everything is working. For each question, please add the text of the question, the code chunks and your answer.


Simulating the data

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.

In the first part of this lab we are going to replicate some of the ideas presented in a post written by Michael Clark. You may consider reading the post before continuing.

We are going to use the faux package to simulate nested data (observations nested within clusters). First, we define the number of clusters n_cluster and the number of observations in each cluster, obs_per_cluster. For example, we might want to have 20 clusters with 4 observations in each cluster (to keep things simple, let’s stick to a “balanced” data-set).

Now, let’s generate some data, where (level 1) observed outcomes are related to predictors in the following manner:
Y=ai+bi⋅X+ϵ
where: ϵ∼N(0,σ2)

But rather than being regular population parameters, ai and bi are random intercepts and slopes, such that each cluster has its own, unique intercept and slope. The random intercept is a level 2 random effect:

ai=α0+ui
where: ui∼N(0,σ2u)
And the random slope is a level 2 random effect:
bi=β0+vi
where: vi∼N(0,σ2v)

To keep things simple, we will make sure that the random intercepts and slopes are independent, that is, the correlation between ui,vi is zero ρu,v=0.

As you can see, in this stage we have only one predictor at level one X . We have no predictor at level 2. We also have to define six different population parameters. For example, we can choose α0=1,β0=0.5 and three different standard deviations: σ=1,σu=0.5,σv=0.25,ρu,v=0.

Feel free to change these values if you would like to simulate different data.

Finally, here is the code that simulates our data in several steps. Run every step separately, and observe the data frame View(df) to its contents

#Define number of clusters and observations
obs_per_cluster <-  20
n_cluster <-  30

#Define parameters:

# Fixed intercept
alpha_0 <-  4 

# Fixed slope
beta_0 <- 0.66

# Residuals st.dev (level 1) 
sig  <-  0.1

# Random intercept st.dev (level 2) 
sig_u <-  0.4

# Random slope st.dev (level 2)
sig_v <- 0.2

# Independent random effects
cor <- 0.3


# 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 -> An empty dataset is made with labels for each cluster and each measurement as defined in n_cluster and obs_per_cluster
df %>%
  print(n = 15)
## # A tibble: 600 × 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 cluster01 obs11
## 12 cluster01 obs12
## 13 cluster01 obs13
## 14 cluster01 obs14
## 15 cluster01 obs15
## # ℹ 585 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 -> Each cluster has been given the fixed intercept and slope, and added to that each cluster gets their own level 2 random intercepts and slopes that lead to an overal sig u of 0.4 and sig v of 0.3
df %>%
  print(n = 15)
## # A tibble: 600 × 6
##    cluster   obs     u_i    v_i   a_i   b_i
##    <chr>     <chr> <dbl>  <dbl> <dbl> <dbl>
##  1 cluster01 obs01 0.836 -0.153  4.84 0.507
##  2 cluster01 obs02 0.836 -0.153  4.84 0.507
##  3 cluster01 obs03 0.836 -0.153  4.84 0.507
##  4 cluster01 obs04 0.836 -0.153  4.84 0.507
##  5 cluster01 obs05 0.836 -0.153  4.84 0.507
##  6 cluster01 obs06 0.836 -0.153  4.84 0.507
##  7 cluster01 obs07 0.836 -0.153  4.84 0.507
##  8 cluster01 obs08 0.836 -0.153  4.84 0.507
##  9 cluster01 obs09 0.836 -0.153  4.84 0.507
## 10 cluster01 obs10 0.836 -0.153  4.84 0.507
## 11 cluster01 obs11 0.836 -0.153  4.84 0.507
## 12 cluster01 obs12 0.836 -0.153  4.84 0.507
## 13 cluster01 obs13 0.836 -0.153  4.84 0.507
## 14 cluster01 obs14 0.836 -0.153  4.84 0.507
## 15 cluster01 obs15 0.836 -0.153  4.84 0.507
## # ℹ 585 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 -> the random effects (x, so the individual values for the x-value) and the random error epsilon. Each individual's y value has also been calculated by adding all values into the model
df %>%
  print(n = 20)
## # A tibble: 600 × 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.836 -0.153  4.84 0.507 -0.456   0.0136  4.62
##  2 cluster01 obs02 0.836 -0.153  4.84 0.507  0.0190 -0.0262  4.82
##  3 cluster01 obs03 0.836 -0.153  4.84 0.507 -0.318   0.0211  4.70
##  4 cluster01 obs04 0.836 -0.153  4.84 0.507 -0.550   0.0239  4.58
##  5 cluster01 obs05 0.836 -0.153  4.84 0.507  1.47    0.102   5.68
##  6 cluster01 obs06 0.836 -0.153  4.84 0.507 -0.287   0.0527  4.74
##  7 cluster01 obs07 0.836 -0.153  4.84 0.507  0.422   0.0145  5.06
##  8 cluster01 obs08 0.836 -0.153  4.84 0.507 -0.0691  0.0881  4.89
##  9 cluster01 obs09 0.836 -0.153  4.84 0.507 -1.76   -0.0238  3.92
## 10 cluster01 obs10 0.836 -0.153  4.84 0.507 -2.52    0.0748  3.63
## 11 cluster01 obs11 0.836 -0.153  4.84 0.507  1.36   -0.141   5.38
## 12 cluster01 obs12 0.836 -0.153  4.84 0.507  0.445  -0.0679  4.99
## 13 cluster01 obs13 0.836 -0.153  4.84 0.507 -0.868  -0.0583  4.34
## 14 cluster01 obs14 0.836 -0.153  4.84 0.507  0.760  -0.215   5.01
## 15 cluster01 obs15 0.836 -0.153  4.84 0.507 -1.04    0.0500  4.36
## 16 cluster01 obs16 0.836 -0.153  4.84 0.507 -0.187  -0.191   4.55
## 17 cluster01 obs17 0.836 -0.153  4.84 0.507  0.404   0.154   5.19
## 18 cluster01 obs18 0.836 -0.153  4.84 0.507  1.27    0.0687  5.55
## 19 cluster01 obs19 0.836 -0.153  4.84 0.507 -1.25    0.0868  4.29
## 20 cluster01 obs20 0.836 -0.153  4.84 0.507  0.164  -0.0675  4.85
## # ℹ 580 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 - only the cluster id, x and y are selected and are left in the final data frame
df %>%
  print(n = 20)
## # A tibble: 600 × 3
##    cluster         x     y
##    <chr>       <dbl> <dbl>
##  1 cluster01 -0.456   4.62
##  2 cluster01  0.0190  4.82
##  3 cluster01 -0.318   4.70
##  4 cluster01 -0.550   4.58
##  5 cluster01  1.47    5.68
##  6 cluster01 -0.287   4.74
##  7 cluster01  0.422   5.06
##  8 cluster01 -0.0691  4.89
##  9 cluster01 -1.76    3.92
## 10 cluster01 -2.52    3.63
## 11 cluster01  1.36    5.38
## 12 cluster01  0.445   4.99
## 13 cluster01 -0.868   4.34
## 14 cluster01  0.760   5.01
## 15 cluster01 -1.04    4.36
## 16 cluster01 -0.187   4.55
## 17 cluster01  0.404   5.19
## 18 cluster01  1.27    5.55
## 19 cluster01 -1.25    4.29
## 20 cluster01  0.164   4.85
## # ℹ 580 more rows

We will then test the data against three types of models:

-\(Complete pooling\): This model ignores the structure of the data, taking all observations to be uncorrelated and independent of one another. The model estimates just two fixed population parameters: the global intercept \(β0\) and the global slope β1 , and the formula you will use in your linear regression model is \(y ~ x\).

-\(No pooling\): This model expands on the previous one. In addition to the global intercept and slope, we add the cluster (categorical) variable and estimate a coefficient for each cluster. In effect, each cluster is associated with a cluster specific intercept. Since we know that there is a variation in the slopes, you may also test a model with an interaction between the clusters and the predictor, x. The formula you will use in your linear regression model is \(y ~ x + cluster\) for the model without the interaction and \(y ~ x + cluster + x:cluster\) for the model with the interaction.

-\(Multilevel model (partial pooling)\): This model also expands on the Complete pooling model to account for the correlated observations within the clusters. But instead of using fixed (dummy) variables, this model uses a random intercept (and, optionally, a random slope). The formula you will use for the random intercept model is \(y ~ x + (1 | cluster)\) and the formula or the random intercept and slope model is \(y ~ x + (x | cluster)\).


Exercise 1

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.

Further explanation and exploration: Use your imagination (and curiosity) to explore your simulations and your models. For example, you may want to compare multiple simulations with the same parameters, and see how they vary. You may want to change the sample size (the number of clusters and observations in each cluster), or you might want to increase the parameters, turn some of them to be negative, or just run multiple simulations with the same parameters, comparing the variation between one simulation and the next. Do the estimates vary a lot between simulations? Does increasing the sample size increase accuracy of the estimates? Does it influence the standard errors? Is there one single model that is superior to all the rest in terms of estimating the parameters? If so which model is it and in what way is it better? If not, which model works best for what purpose?

Calculating the ICC: The calculation of the ICC is straightforward when we only have random intercepts. Taking the random slopes into account complicates the situation because in that case, the ICC varies with the predictors. Because here the predictor is normally distributed around zero, the calculation of the ICC (at x=0) reduces to the regular form of the ICC, which need not take the random slope into account.

For example, in the example below, data is simulated with 30 clusters, 20 observations per cluster, a global intercept of 2 and a global slope of 1.5, the variance of the (level-one) residual is 1, the variance of the random intercept and the random slope are 1.52 and 1.82 respectively, and the correlation coefficient is 0.5.

You can see that the no-pooling models have larger standard errors for the intercept, probably because the estimation is based on data from one single cluster (the reference cluster with 20 observations and a small number of residual degrees of freedom). The no-pooling model with interactions is suffering from relatively large standard errors (most probably due to a small number of residual degrees of freedom). Also, note that for the no-pooling model, the global intercept is associated with the intercept of the reference cluster. So you are bound to get an estimate that is in effect the sum of the global intercept and the random intercept of the first cluster (=α0+u1)

Several approaches can be used to calculate the confidence intervals of random effects in multilevel models, each with its own strengths and limitations. Here are three of the most common methods:

Parametric Confidence Intervals: This approach is based on the assumption that the random effects follow a normal distribution. The standard errors of the random effects are estimated from the model and used to compute confidence intervals using the normal distribution. This method is straightforward and computationally efficient, but it may be inaccurate if the actual distribution of the random effects deviates significantly from normality. To calculate parametric confidence intervals, use the augment function from the broom.mixed package.

Bootstrap Confidence Intervals: Bootstrapping is a non-parametric method that involves repeatedly resampling the data with replacement and refitting the model each time. The resulting distribution of the random effects from these multiple fits is used to construct bootstrap confidence intervals. This method is more robust to non-normality than parametric methods, but it can be computationally intensive, especially for large datasets. To calculate bootstrap confidence intervals, use the predictInterval function from the merTools package.

Bayesian Credible Intervals: Bayesian multilevel models use a probability distribution to represent the uncertainty in the model parameters, including the random effects. Credible intervals are derived from the posterior distribution of the random effects, which reflects the combined information from the data and the prior distribution. Bayesian methods are more flexible and can handle complex hierarchical structures, but they may require more expertise and computational resources compared to frequentist methods.

Each method provides a different estimate of the confidence intervals of random effects in multilevel models and there is no single “correct” approach. The choice of method should be guided by the specific characteristics of the data, the research question and the researchers philosophy. For simpler models and relatively large sample sizes, parametric methods may be sufficient. For more complex models or smaller datasets, bootstrap or Bayesian methods may be more appropriate. Additionally, the interpretation of confidence intervals for random effects depends on the type of inference being made. For example, conditional confidence intervals and marginal confidence intervals are used for different purposes.

#Three types of models

M1 <- lm(y ~ x, df)
summary(M1)
## 
## Call:
## lm(formula = y ~ x, data = df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.60903 -0.30678 -0.02135  0.28554  1.34907 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  4.03633    0.01999  201.88   <2e-16 ***
## x            0.69540    0.02125   32.72   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.4897 on 598 degrees of freedom
## Multiple R-squared:  0.6416, Adjusted R-squared:  0.641 
## F-statistic:  1070 on 1 and 598 DF,  p-value: < 2.2e-16
M2 <- lm(y ~ x + cluster, df)
summary(M2)
## 
## Call:
## lm(formula = y ~ x + cluster, data = df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.69426 -0.11589  0.00747  0.10950  0.75200 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       4.860185   0.044913 108.213  < 2e-16 ***
## x                 0.684027   0.008929  76.606  < 2e-16 ***
## clustercluster02 -0.254984   0.063503  -4.015 6.73e-05 ***
## clustercluster03 -1.156971   0.063494 -18.222  < 2e-16 ***
## clustercluster04 -0.730007   0.063500 -11.496  < 2e-16 ***
## clustercluster05 -0.196245   0.063655  -3.083  0.00215 ** 
## clustercluster06 -0.715941   0.063640 -11.250  < 2e-16 ***
## clustercluster07  0.049706   0.063551   0.782  0.43446    
## clustercluster08 -1.129040   0.063650 -17.738  < 2e-16 ***
## clustercluster09 -1.202209   0.063491 -18.935  < 2e-16 ***
## clustercluster10 -1.270297   0.063542 -19.991  < 2e-16 ***
## clustercluster11 -0.967001   0.063490 -15.231  < 2e-16 ***
## clustercluster12 -1.373693   0.063501 -21.633  < 2e-16 ***
## clustercluster13 -1.312388   0.063512 -20.663  < 2e-16 ***
## clustercluster14 -0.983023   0.063588 -15.459  < 2e-16 ***
## clustercluster15 -0.683371   0.063512 -10.760  < 2e-16 ***
## clustercluster16 -0.504738   0.063491  -7.950 1.01e-14 ***
## clustercluster17 -1.297632   0.063502 -20.435  < 2e-16 ***
## clustercluster18 -0.785838   0.063507 -12.374  < 2e-16 ***
## clustercluster19 -0.004801   0.063489  -0.076  0.93975    
## clustercluster20 -0.705197   0.063699 -11.071  < 2e-16 ***
## clustercluster21 -0.798853   0.063497 -12.581  < 2e-16 ***
## clustercluster22 -0.762498   0.063507 -12.007  < 2e-16 ***
## clustercluster23 -0.633156   0.063490  -9.973  < 2e-16 ***
## clustercluster24 -1.168361   0.063493 -18.401  < 2e-16 ***
## clustercluster25 -0.647631   0.063489 -10.201  < 2e-16 ***
## clustercluster26 -0.756796   0.063491 -11.920  < 2e-16 ***
## clustercluster27 -0.697737   0.063499 -10.988  < 2e-16 ***
## clustercluster28 -2.007087   0.063489 -31.613  < 2e-16 ***
## clustercluster29 -0.993882   0.063585 -15.631  < 2e-16 ***
## clustercluster30 -1.028575   0.063490 -16.201  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2008 on 569 degrees of freedom
## Multiple R-squared:  0.9427, Adjusted R-squared:  0.9397 
## F-statistic: 311.9 on 30 and 569 DF,  p-value: < 2.2e-16
M3 <- lm(y ~ x + cluster + x:cluster, df)
summary(M3)
## 
## Call:
## lm(formula = y ~ x + cluster + x:cluster, data = df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.34565 -0.06463 -0.00008  0.06962  0.29539 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         4.83099    0.02325 207.799  < 2e-16 ***
## x                   0.48886    0.02305  21.209  < 2e-16 ***
## clustercluster02   -0.22586    0.03270  -6.908 1.39e-11 ***
## clustercluster03   -1.13485    0.03272 -34.685  < 2e-16 ***
## clustercluster04   -0.70442    0.03270 -21.542  < 2e-16 ***
## clustercluster05   -0.19451    0.03447  -5.642 2.71e-08 ***
## clustercluster06   -0.78476    0.03337 -23.515  < 2e-16 ***
## clustercluster07    0.07539    0.03302   2.283 0.022800 *  
## clustercluster08   -0.97934    0.03387 -28.918  < 2e-16 ***
## clustercluster09   -1.14715    0.03327 -34.478  < 2e-16 ***
## clustercluster10   -1.20216    0.03290 -36.542  < 2e-16 ***
## clustercluster11   -0.94326    0.03277 -28.787  < 2e-16 ***
## clustercluster12   -1.34601    0.03270 -41.165  < 2e-16 ***
## clustercluster13   -1.24740    0.03350 -37.238  < 2e-16 ***
## clustercluster14   -1.03236    0.03313 -31.161  < 2e-16 ***
## clustercluster15   -0.65640    0.03271 -20.069  < 2e-16 ***
## clustercluster16   -0.44256    0.03334 -13.276  < 2e-16 ***
## clustercluster17   -1.26760    0.03270 -38.768  < 2e-16 ***
## clustercluster18   -0.75120    0.03270 -22.971  < 2e-16 ***
## clustercluster19    0.04846    0.03288   1.474 0.141061    
## clustercluster20   -0.63190    0.03479 -18.164  < 2e-16 ***
## clustercluster21   -0.80830    0.03331 -24.269  < 2e-16 ***
## clustercluster22   -0.73470    0.03270 -22.467  < 2e-16 ***
## clustercluster23   -0.59119    0.03284 -18.004  < 2e-16 ***
## clustercluster24   -1.14173    0.03274 -34.871  < 2e-16 ***
## clustercluster25   -0.67100    0.03368 -19.920  < 2e-16 ***
## clustercluster26   -0.73500    0.03277 -22.427  < 2e-16 ***
## clustercluster27   -0.69429    0.03425 -20.272  < 2e-16 ***
## clustercluster28   -2.02712    0.03302 -61.386  < 2e-16 ***
## clustercluster29   -0.95229    0.03314 -28.736  < 2e-16 ***
## clustercluster30   -0.98140    0.03345 -29.339  < 2e-16 ***
## x:clustercluster02  0.46505    0.03113  14.939  < 2e-16 ***
## x:clustercluster03  0.06442    0.03193   2.017 0.044146 *  
## x:clustercluster04 -0.04018    0.03513  -1.144 0.253292    
## x:clustercluster05  0.27045    0.03780   7.156 2.73e-12 ***
## x:clustercluster06  0.48263    0.03026  15.950  < 2e-16 ***
## x:clustercluster07  0.21631    0.03600   6.008 3.46e-09 ***
## x:clustercluster08 -0.14215    0.03378  -4.207 3.02e-05 ***
## x:clustercluster09  0.31606    0.03688   8.570  < 2e-16 ***
## x:clustercluster10 -0.07793    0.03438  -2.267 0.023794 *  
## x:clustercluster11  0.13983    0.03173   4.407 1.26e-05 ***
## x:clustercluster12  0.03734    0.03641   1.025 0.305610    
## x:clustercluster13  0.29915    0.03129   9.560  < 2e-16 ***
## x:clustercluster14  0.51052    0.03148  16.217  < 2e-16 ***
## x:clustercluster15  0.24881    0.03045   8.172 2.17e-15 ***
## x:clustercluster16  0.35531    0.03908   9.092  < 2e-16 ***
## x:clustercluster17  0.33346    0.03266  10.210  < 2e-16 ***
## x:clustercluster18 -0.07831    0.03847  -2.036 0.042257 *  
## x:clustercluster19  0.32927    0.02991  11.010  < 2e-16 ***
## x:clustercluster20  0.09253    0.03600   2.571 0.010415 *  
## x:clustercluster21  0.04974    0.03317   1.500 0.134273    
## x:clustercluster22  0.26007    0.03542   7.342 7.80e-13 ***
## x:clustercluster23  0.31670    0.03680   8.605  < 2e-16 ***
## x:clustercluster24  0.15624    0.03469   4.504 8.18e-06 ***
## x:clustercluster25 -0.10441    0.05159  -2.024 0.043477 *  
## x:clustercluster26  0.11456    0.03350   3.419 0.000675 ***
## x:clustercluster27  0.10211    0.04346   2.350 0.019157 *  
## x:clustercluster28 -0.14829    0.03967  -3.739 0.000205 ***
## x:clustercluster29  0.14409    0.03203   4.499 8.36e-06 ***
## x:clustercluster30  0.28710    0.04283   6.704 5.13e-11 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.1028 on 540 degrees of freedom
## Multiple R-squared:  0.9857, Adjusted R-squared:  0.9842 
## F-statistic: 632.3 on 59 and 540 DF,  p-value: < 2.2e-16
M4 <- lmer(y ~ x + (1 | cluster) ,df)
summary(M4)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: y ~ x + (1 | cluster)
##    Data: df
## 
## REML criterion at convergence: -76.2
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.4737 -0.5745  0.0409  0.5404  3.7367 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  cluster  (Intercept) 0.20583  0.4537  
##  Residual             0.04031  0.2008  
## Number of obs: 600, groups:  cluster, 30
## 
## Fixed effects:
##              Estimate Std. Error        df t value Pr(>|t|)    
## (Intercept) 4.036e+00  8.324e-02 2.900e+01   48.49   <2e-16 ***
## x           6.841e-01  8.927e-03 5.696e+02   76.64   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Correlation of Fixed Effects:
##   (Intr)
## x 0.001
M5<- lmer(y ~ x + (x|cluster) ,df)
summary(M5)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: y ~ x + (x | cluster)
##    Data: df
## 
## REML criterion at convergence: -725.8
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.3566 -0.6396  0.0048  0.6744  2.8970 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr
##  cluster  (Intercept) 0.20596  0.4538       
##           x           0.03426  0.1851   0.28
##  Residual             0.01057  0.1028       
## Number of obs: 600, groups:  cluster, 30
## 
## Fixed effects:
##             Estimate Std. Error       df t value Pr(>|t|)    
## (Intercept)  4.03418    0.08297 29.00151   48.62   <2e-16 ***
## x            0.65628    0.03415 28.97483   19.22   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Correlation of Fixed Effects:
##   (Intr)
## x 0.276
# Displaying the four models by each other
modelsummary(
  list(
    "Complete pooling" = M1, 
    "No pooling" = M2,
    "No pooling + interaction" = M3,
    "Multilevel model"= M4 ,
    "Multilevel model + random slopes"= M5), 
  stars = TRUE
  )
Complete pooling No pooling No pooling + interaction Multilevel model Multilevel model + random slopes
(Intercept) 4.036*** 4.860*** 4.831*** 4.036*** 4.034***
(0.020) (0.045) (0.023) (0.083) (0.083)
x 0.695*** 0.684*** 0.489*** 0.684*** 0.656***
(0.021) (0.009) (0.023) (0.009) (0.034)
clustercluster02 −0.255*** −0.226***
(0.064) (0.033)
clustercluster03 −1.157*** −1.135***
(0.063) (0.033)
clustercluster04 −0.730*** −0.704***
(0.064) (0.033)
clustercluster05 −0.196** −0.195***
(0.064) (0.034)
clustercluster06 −0.716*** −0.785***
(0.064) (0.033)
clustercluster07 0.050 0.075*
(0.064) (0.033)
clustercluster08 −1.129*** −0.979***
(0.064) (0.034)
clustercluster09 −1.202*** −1.147***
(0.063) (0.033)
clustercluster10 −1.270*** −1.202***
(0.064) (0.033)
clustercluster11 −0.967*** −0.943***
(0.063) (0.033)
clustercluster12 −1.374*** −1.346***
(0.064) (0.033)
clustercluster13 −1.312*** −1.247***
(0.064) (0.033)
clustercluster14 −0.983*** −1.032***
(0.064) (0.033)
clustercluster15 −0.683*** −0.656***
(0.064) (0.033)
clustercluster16 −0.505*** −0.443***
(0.063) (0.033)
clustercluster17 −1.298*** −1.268***
(0.064) (0.033)
clustercluster18 −0.786*** −0.751***
(0.064) (0.033)
clustercluster19 −0.005 0.048
(0.063) (0.033)
clustercluster20 −0.705*** −0.632***
(0.064) (0.035)
clustercluster21 −0.799*** −0.808***
(0.063) (0.033)
clustercluster22 −0.762*** −0.735***
(0.064) (0.033)
clustercluster23 −0.633*** −0.591***
(0.063) (0.033)
clustercluster24 −1.168*** −1.142***
(0.063) (0.033)
clustercluster25 −0.648*** −0.671***
(0.063) (0.034)
clustercluster26 −0.757*** −0.735***
(0.063) (0.033)
clustercluster27 −0.698*** −0.694***
(0.063) (0.034)
clustercluster28 −2.007*** −2.027***
(0.063) (0.033)
clustercluster29 −0.994*** −0.952***
(0.064) (0.033)
clustercluster30 −1.029*** −0.981***
(0.063) (0.033)
x × clustercluster02 0.465***
(0.031)
x × clustercluster03 0.064*
(0.032)
x × clustercluster04 −0.040
(0.035)
x × clustercluster05 0.270***
(0.038)
x × clustercluster06 0.483***
(0.030)
x × clustercluster07 0.216***
(0.036)
x × clustercluster08 −0.142***
(0.034)
x × clustercluster09 0.316***
(0.037)
x × clustercluster10 −0.078*
(0.034)
x × clustercluster11 0.140***
(0.032)
x × clustercluster12 0.037
(0.036)
x × clustercluster13 0.299***
(0.031)
x × clustercluster14 0.511***
(0.031)
x × clustercluster15 0.249***
(0.030)
x × clustercluster16 0.355***
(0.039)
x × clustercluster17 0.333***
(0.033)
x × clustercluster18 −0.078*
(0.038)
x × clustercluster19 0.329***
(0.030)
x × clustercluster20 0.093*
(0.036)
x × clustercluster21 0.050
(0.033)
x × clustercluster22 0.260***
(0.035)
x × clustercluster23 0.317***
(0.037)
x × clustercluster24 0.156***
(0.035)
x × clustercluster25 −0.104*
(0.052)
x × clustercluster26 0.115***
(0.034)
x × clustercluster27 0.102*
(0.043)
x × clustercluster28 −0.148***
(0.040)
x × clustercluster29 0.144***
(0.032)
x × clustercluster30 0.287***
(0.043)
SD (Intercept cluster) 0.454 0.454
SD (x cluster) 0.185
Cor (Intercept~x cluster) 0.279
SD (Observations) 0.201 0.103
Num.Obs. 600 600 600 600 600
R2 0.642 0.943 0.986
R2 Adj. 0.641 0.940 0.984
R2 Marg. 0.628 0.608
R2 Cond. 0.939 0.983
AIC 850.0 −191.8 −968.2 −68.2 −713.8
BIC 863.2 −51.1 −700.0 −50.6 −687.4
ICC 0.8 1.0
Log.Lik. −422.004 127.912 545.108
F 1070.463 311.930 632.347
RMSE 0.49 0.20 0.10 0.20 0.10
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Note:The following answer is based on a previous iteration of the prediction
Conclusion: The completely pooled data, and the two mixed effects models are closest to the original parameter for the intercept (alpha_0 = 4). These three models are also closest to the slope (beta-zero) for x at 0.66, with the complete_pool model actually being the closest. Only the multilevel models have estimates of the intercept, which are both relatively low (slightly better in the random intercept model compared to the random slopes). The random slope estimate of the random slope model is 0.256, relatively close to the set value of 0.3. The correlation value of the random slope model is very low (0.007 compared to the set value of 0.6), and the SD of the observations are quite close to the set value of 2 for both models. The completely pooled model and the random effects models seem to be the best in this case, the completely pooled model even has a slightly lower AIC and BIC than the two multilevel ones, possibly due to increased model complexity. All of these seem to be better than the no pool models, however.


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?

To create the caterpillar plot, you can use the following code. Don’t forget to fill in the gaps. See the appendix below for more information about the caterpillar plots, their use and their interpretation.

# 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) 

# 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!
predict_y  %>%  
  ggplot(aes(xmin = lb, xmax = ub, y = level, x = estimate)) + 
    geom_pointrange( ) + 
    labs(x = "Cluster Intercepts", y = NULL, title = "Random Effect caterpilar plot (Intercepts)")

Aswer: To create the lattice plot and the spaghetti plot, you can use the code below. See the appendix below for more information about these different plots, their use and their interpretation.

predictions(mdl_multilevel)  %>% 
  ggplot(aes(x = x, y = y, color = cluster)) + 
  geom_point() + 
  geom_line(aes(y = estimate))+ theme(legend.position = 'none') +
  labs(title = "Simulated data: Spaghetti plot",
        subtitle= "Random intercept with random slope")

predictions(mdl_multilevel)  %>% 
  ggplot(aes(x = x, y = y, color = cluster)) + 
  geom_point() + 
  geom_line(aes(y = estimate)) + 
  facet_wrap(~ cluster,) + theme(legend.position = 'none') +
  labs(title = "Simulated data:lattice plot",
        subtitle= "Random intercept with random slope")

Answer: There are a advantages to used the spaghetti and lattice plots, because is possible to compare the differences (slope) across clusters.


Radon in the home: a case study 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 Gelman 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.

radon_mn <- read_rds("https://bit.ly/BMLR-Radon")  %>%  
  filter(state == "MN")  %>% 
  # drop counties without measurements
  mutate(county = fct_drop(county))

Exercise 3

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

# Write your code here
radon_mn %>%
  count(county) %>%  arrange(desc(n)) 
 radon1 <- radon_mn %>%
  filter(county %in% c("ST LOUIS", "HENNEPIN", "DAKOTA", "ANOKA", "WASHINGTON")) 
table1( ~radon +log.radon+ county_index  + fullfips+ u | county*first_floor,data = radon1,
        overall=F, caption = "Measurements of the gas Radon")
## Warning in table1.formula(~radon + log.radon + county_index + fullfips + :
## Terms to the right of '|' in formula 'x' define table columns and are expected
## to be factors with meaningful labels.
Measurements of the gas Radon
ANOKA
DAKOTA
HENNEPIN
ST LOUIS
WASHINGTON
0
(N=49)
1
(N=3)
0
(N=59)
1
(N=4)
0
(N=94)
1
(N=11)
0
(N=100)
1
(N=16)
0
(N=41)
1
(N=5)
radon
Mean (SD) 3.08 (2.03) 1.03 (0.802) 4.92 (3.57) 1.68 (0.838) 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.40 [0.500, 21.2] 1.55 [0.800, 2.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]
log.radon
Mean (SD) 0.903 (0.699) -0.309 (1.15) 1.35 (0.731) 0.418 (0.518) 1.37 (0.641) 0.531 (0.852) 0.846 (0.776) 0.282 (0.799) 1.37 (0.757) 0.318 (0.428)
Median [Min, Max] 0.875 [-0.916, 2.09] 0.0953 [-1.61, 0.588] 1.48 [-0.693, 3.05] 0.434 [-0.223, 1.03] 1.39 [-0.916, 3.16] 0.742 [-0.916, 2.03] 0.765 [-1.61, 3.47] 0.283 [-0.916, 1.97] 1.46 [-0.223, 3.02] 0.182 [-0.223, 0.916]
county_index
Mean (SD) 8.00 (0) 8.00 (0) 84.0 (0) 84.0 (0) 141 (0) 141 (0) 323 (0) 323 (0) 366 (0) 366 (0)
Median [Min, Max] 8.00 [8.00, 8.00] 8.00 [8.00, 8.00] 84.0 [84.0, 84.0] 84.0 [84.0, 84.0] 141 [141, 141] 141 [141, 141] 323 [323, 323] 323 [323, 323] 366 [366, 366] 366 [366, 366]
fullfips
Mean (SD) 27000 (0) 27000 (0) 27000 (0) 27000 (0) 27100 (0) 27100 (0) 27100 (0) 27100 (0) 27200 (0) 27200 (0)
Median [Min, Max] 27000 [27000, 27000] 27000 [27000, 27000] 27000 [27000, 27000] 27000 [27000, 27000] 27100 [27100, 27100] 27100 [27100, 27100] 27100 [27100, 27100] 27100 [27100, 27100] 27200 [27200, 27200] 27200 [27200, 27200]
u
Mean (SD) -0.847 (0) -0.847 (0) -0.0241 (0) -0.0241 (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.0241 [-0.0241, -0.0241] -0.0241 [-0.0241, -0.0241] -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]
#Write your code here

radon_mn %>% glimpse()
## Rows: 919
## Columns: 8
## $ state        <fct> MN, MN, MN, MN, MN, MN, MN, MN, MN, MN, MN, MN, MN, MN, M…
## $ county       <fct> AITKIN, AITKIN, AITKIN, AITKIN, ANOKA, ANOKA, ANOKA, ANOK…
## $ radon        <dbl> 2.2, 2.2, 2.9, 1.0, 3.1, 2.5, 1.5, 1.0, 0.7, 1.2, 1.2, 1.…
## $ log.radon    <dbl> 0.78845736, 0.78845736, 1.06471074, 0.00000000, 1.1314021…
## $ first_floor  <int> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ county_index <dbl> 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, …
## $ fullfips     <dbl> 27001, 27001, 27001, 27001, 27003, 27003, 27003, 27003, 2…
## $ u            <dbl> -0.6890476, -0.6890476, -0.6890476, -0.6890476, -0.847312…
GGally::ggpairs(radon_mn, columns = c(3:6,8), title = "Measurements of the gas Radon",
        upper = list(combo = "box_no_facet", discrete = "facetbar",
                na = "na"),
        lower = list(combo = "dot_no_facet", discrete = "colbar",
                  na = "na"),
        mapping = ggplot2::aes(colour = as.factor(first_floor)),
        legend = 1,
        )
## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

## Warning in cor(x, y): the standard deviation is zero

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.

First, we need to associate each county with the number of observations.

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.
A  <- 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))  +
  geom_hline(yintercept = 1.2) +
  scale_x_continuous(trans = 'log10')+
  geom_pointrange(position = position_jitter(width = 0.5, height = 0)) + 
 labs(y = "Estimated log radon in the county",x = "Number of observations", title = "No pooling (fixed efects)") + 
  scale_x_continuous(trans = 'log10')
## Scale for x is already present.
## Adding another scale for x, which will replace the existing scale.
B <- 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(trans = 'log10') + 
  geom_hline(yintercept = 1.2) +
  geom_pointrange(position = position_jitter(width = 0.5, height = 0)) + 
 labs(y = "Estimated log radon in the county",x = "Number of observations", title = "Partial pooling (multilevel model)") 


ggpubr::ggarrange(A,B, common.legend = TRUE, ncol = 1, nrow = 2)

Answer
When we use the no pooling method, the estimates become less precise and more sensitive to individual data points, resulting in higher variability.

for the No-pooling Analysis, it has two advantages:1) Flexibility: No-pooling allows for individual estimates for each county, providing a detailed view of each unit, 2) Fine-grained Analysis: It captures local variations and nuances in each county’s data. However, it also has disadvantages: 1) Increased Variability: As seen in the figures, estimates for counties with fewer measurements are more variable and have larger standard errors; 2) This is a consequence of relying solely on the limited data available for each county.

For Multilevel Model (Pooling Information): it has advantages: 1) Borrowing Strength: Multilevel models pool information across units (counties, in this case), allowing for more stable estimates, especially for units with limited data. 2) Improved Precision: By sharing information, the model can provide more reliable estimates for counties with fewer measurements. However, it may has the risk of over-smoothing. In some cases, the model may excessively smooth estimates, potentially missing local variations present in individual units.

Conclusion:

In summary, the main advantage of a no-pooling analysis is its flexibility and ability to capture local variations. However, this comes at the cost of increased variability and larger standard errors, especially for units with fewer measurements. The multilevel model addresses this issue by borrowing strength across units, providing more stable estimates, but it may risk oversmoothing and miss local nuances. The choice between the two approaches depends on the research question and the trade-off between detailed local insights and more robust, pooled estimates.

The counties with fewer observations have a larger standard error, as there is more variability. This is where the main advantage of the multilevel model over the non-clustered model is that it shows a better fit, due to the random effect that adjusts the slope.

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?

The three lines show the predictions of the three models: the complete pooling in red, the no pooling (dashed black line) and the multilevel (partial pooling) model (blue line). You can see that the complete pooling model does not vary with the county level, showing the exact same intercept and slope at each cell in the lattice. The no pooling model is very sensitive to the data in the county: even when there are just two observations, such as in the county of Mille Lacs, we see the no pooling model connecting the two dots. This shows how a no-pooling approach tends to over-fit the data. The multilevel model finds a compromise between the no pooling and the complete pooling models. It introduces some bias, but avoids over fitting and is more useful for generalizations.

Hints To create the figure, you will need to plot the data itself as dots using the ’geom_point()` layer, and then add the three models, one layer at a time. To simplify, I will provide the code for one model and you can add the rest yourselves.

# Fit the model (you will need to fit all three models)

m.No_pooling <- lm(log.radon ~ first_floor + county, data = radon_mn)
m.complete_pooling <- lm(log.radon ~ first_floor, data = radon_mn)
m.multilevel <- lmer(log.radon ~ first_floor + (first_floor | county), data = radon_mn)

# Collect the predictions
pred_nopool <-m.no_pool  %>% 
  predictions(newdata = datagrid(first_floor = c(0, 1),
  county = c("BLUE EARTH", "CLAY", "DAKOTA", "DOUGLAS","KOOCHICHING", 
               "LAC QUI PARLE", "MCLEOD", "MILLE LACS","MOWER", "OTTER TAIL",
               "RAMSEY", "REDWOOD","RICE", "SCOTT", "ST LOUIS", "STEARNS"))) %>%
  select(county, first_floor, estimate, conf.low, conf.high) %>%
  as_tibble( )  
## Warning: Some of the variable names are missing from the model data:
## first_floor
pred_complete_pooling  <- m.complete_pooling  %>% 
  predictions(newdata = datagrid(first_floor = c(0, 1),
    county = c("BLUE EARTH", "CLAY", "DAKOTA", "DOUGLAS","KOOCHICHING", 
               "LAC QUI PARLE", "MCLEOD", "MILLE LACS","MOWER", "OTTER TAIL",
               "RAMSEY", "REDWOOD","RICE", "SCOTT", "ST LOUIS", "STEARNS"))) %>%
  select(county, first_floor, estimate, conf.low, conf.high) %>%
  as_tibble( )  
## Warning: Some of the variable names are missing from the model data: county
pred_multi <- m.multilevel  %>% 
  predictions(newdata = datagrid(first_floor = c(0, 1),
    county = c("BLUE EARTH", "CLAY", "DAKOTA", "DOUGLAS","KOOCHICHING", 
               "LAC QUI PARLE", "MCLEOD", "MILLE LACS","MOWER", "OTTER TAIL",
               "RAMSEY", "REDWOOD","RICE", "SCOTT", "ST LOUIS", "STEARNS"))) %>%
  select(county, first_floor, estimate, conf.low, conf.high) %>%
  as_tibble( )  

radon_mn %>%
  filter(county %in% c("BLUE EARTH", "CLAY", "DAKOTA", "DOUGLAS",
              "KOOCHICHING", "LAC QUI PARLE", "MCLEOD", "MILLE LACS",
              "MOWER", "OTTER TAIL", "RAMSEY", "REDWOOD",
              "RICE", "SCOTT", "ST LOUIS", "STEARNS")) %>% 
  ggplot(aes(x = first_floor, y = log.radon)) +
  geom_point() + 
  geom_line(data = pred_nopool, aes(x = first_floor, y = estimate), color = "#030303", linetype = "dashed") +
  geom_line(data = pred_complete_pooling, aes(x = first_floor, y = estimate), color = "#CD2626", linetype = "twodash") +
  geom_line(data = pred_multi, aes(x = first_floor, y = estimate), color = "#104E8B")  +
  scale_x_continuous(breaks = c(0, 1), labels = c("floor = 0", "floor = 1")) +
  facet_wrap( ~ county, scales = "free_y")  + labs(y = "Log Radon level", x = "") + theme_gray() +              
  theme(strip.text = element_text(face = "bold"))

Answer For the complete pooling model, different counties have the same slopes and same intercepts, and for the no pooling model, it considers the variance from house and county separately (no interaction in our model), so the plots shows that in different counties, the house have different slopes and intercepts, but the effects of house are fixed.Finally, multilevel model, it considers the nested data structures. In different counties, the effects of house are different, where the house have different slopes and intercepts.

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)

# 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) %>% 
  select(log.radon, u, estimate, conf.low, conf.high)

# predictions for the multilevel model
# stratified by the level of uranium
pred.lvl12 <- predictions( md.lvl12,by = "u") %>%
  select( u, estimate, conf.low, conf.high)


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)) +
  geom_ribbon(data = pred.lm, aes(ymin = conf.low, ymax = conf.high),  alpha = 0.2)+ 
  labs(x="Uranium (County level)", y="County Level coefficients ")+ 
  theme_gray() +              
  theme(strip.text = element_text(face = "bold"))

Answer The dots in the figure shows the coefficients of log radon per county, as predicted with a multilevel model based on the measured county uranium levels. Each county has its own error bar. The straight line shows the linear model prediction of the relationship between county-level uranium and non-pooled level 2 log radon levels. The confidence band around the line shows the 95% confidence interval at the different uranium levels for the linear model, so it can be seen how well the multilevel county predictors fit the linear model. The graph shows that there is a positive linear relationship between county-level coefficients and Uranium levels.

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.

#Checking parameters in models of radon data
mdl_nopool <- lm(log.radon ~ first_floor + county, data = radon_mn)
mdl_completepool <- lm(log.radon ~ first_floor, data = radon_mn)
mdl_multilevel <- lmer(log.radon ~ first_floor + (first_floor | county), data = radon_mn)


#Acquire nr of clusters and observations per cluster
y <- count(radon_mn, 'county')
mean(y$freq) # -> 10.81176 so about 11
## Warning: Unknown or uninitialised column: `freq`.
## Warning in mean.default(y$freq): argument is not numeric or logical: returning
## NA
## [1] NA
##Generating articifical data

#Define number of clusters and observations
obs_per_cluster <-  11
n_cluster <-  85

#Define parameters:

# Fixed intercept
alpha_0 <-  1.463

# Fixed slope
beta_0 <- -0.681

# Residuals st.dev (level 1) 
sig  <-  0.746

# Random intercept st.dev (level 2) 
sig_u <-  0.349

# Random slope st.dev (level 2)
sig_v <- 0.344

# Independent random effects
cor <- -0.337


# Create a dataset that can be reproduced
set.seed(888)  
# step 1: create the units 
df <- add_random(
    county = n_cluster,  # first the clusters
    obs = obs_per_cluster # second, the observations
    ) 

# step 2: Add anything at level 2
# Here we have random intercept/slope 
df <- df %>% 
  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
    )

# step 3: add anything at level 1
df <- df %>% 
  mutate(
    first_floor       = rnorm(n_cluster * obs_per_cluster),
    epsilon = rnorm(n_cluster * obs_per_cluster, 0, sig),
    log.radon = a_i + b_i * first_floor + epsilon
    )

# For the models, we really only need 
# the cluster id, the y and the x

df  <- df %>%select(county, first_floor, log.radon)

# Print the result 
# try to figure out what just happened - only the cluster id, x and y are selected and are left in the final data frame
df %>%
  print(n = 20)
## # A tibble: 935 × 3
##    county   first_floor log.radon
##    <chr>          <dbl>     <dbl>
##  1 county01       0.605    0.898 
##  2 county01      -0.695    3.30  
##  3 county01      -0.837    2.66  
##  4 county01      -0.646    2.62  
##  5 county01       1.44    -1.32  
##  6 county01      -0.661    2.96  
##  7 county01       1.61    -1.99  
##  8 county01       0.116    1.47  
##  9 county01       1.01     1.21  
## 10 county01       1.55    -2.23  
## 11 county01      -1.19     2.43  
## 12 county02       1.27     0.0839
## 13 county02      -1.70     3.98  
## 14 county02       0.951   -1.49  
## 15 county02      -0.446    2.10  
## 16 county02      -0.373    1.29  
## 17 county02      -0.343    0.871 
## 18 county02      -0.643    3.24  
## 19 county02       0.768    0.302 
## 20 county02       0.149    2.24  
## # ℹ 915 more rows
# Make a regression model with the simulated data
mdl_nopool_art <- lm(log.radon ~ first_floor + county, data = df)
mdl_completepool_art <- lm(log.radon ~ first_floor, data = df)
mdl_multilevel_art <- lmer(log.radon ~ first_floor + (first_floor|county), df)

#Compare multilevel model with artificial data to multilevel model to radon data
modelsummary(
  list(
    nopool_art = mdl_nopool_art, 
    nopool_real = mdl_nopool,
    completepool_art = mdl_completepool_art,
    completepool_real = mdl_completepool,
    multilevel_art = mdl_multilevel_art,
    multilevel_real = mdl_multilevel
    ), 
  stars = TRUE
  )
nopool_art nopool_real completepool_art completepool_real multilevel_art multilevel_real
(Intercept) 1.251*** 0.841* 1.420*** 1.327*** 1.439*** 1.463***
(0.246) (0.379) (0.029) (0.030) (0.048) (0.054)
first_floor −0.756*** −0.721*** −0.741*** −0.613*** −0.740*** −0.681***
(0.029) (0.074) (0.030) (0.073) (0.050) (0.088)
countycounty02 0.115
(0.347)
countycounty03 0.109
(0.348)
countycounty04 0.108
(0.347)
countycounty05 0.689*
(0.347)
countycounty06 0.160
(0.348)
countycounty07 1.073**
(0.347)
countycounty08 0.187
(0.347)
countycounty09 0.186
(0.348)
countycounty10 −0.408
(0.347)
countycounty11 0.029
(0.347)
countycounty12 −0.256
(0.348)
countycounty13 0.778*
(0.347)
countycounty14 −0.115
(0.348)
countycounty15 0.314
(0.347)
countycounty16 0.529
(0.347)
countycounty17 0.009
(0.347)
countycounty18 0.513
(0.347)
countycounty19 0.809*
(0.348)
countycounty20 0.400
(0.347)
countycounty21 0.553
(0.347)
countycounty22 0.786*
(0.347)
countycounty23 0.423
(0.348)
countycounty24 −0.184
(0.348)
countycounty25 0.109
(0.348)
countycounty26 0.079
(0.348)
countycounty27 0.002
(0.348)
countycounty28 −0.720*
(0.348)
countycounty29 0.149
(0.347)
countycounty30 0.199
(0.347)
countycounty31 −0.602+
(0.348)
countycounty32 0.863*
(0.347)
countycounty33 −0.027
(0.348)
countycounty34 −0.147
(0.347)
countycounty35 0.136
(0.348)
countycounty36 1.156***
(0.348)
countycounty37 −0.318
(0.347)
countycounty38 −0.436
(0.348)
countycounty39 0.255
(0.348)
countycounty40 0.214
(0.347)
countycounty41 0.018
(0.348)
countycounty42 0.358
(0.348)
countycounty43 0.633+
(0.347)
countycounty44 1.146**
(0.348)
countycounty45 0.480
(0.347)
countycounty46 −0.051
(0.348)
countycounty47 0.419
(0.348)
countycounty48 −0.430
(0.348)
countycounty49 0.597+
(0.347)
countycounty50 −0.561
(0.348)
countycounty51 −0.493
(0.348)
countycounty52 0.575+
(0.348)
countycounty53 0.656+
(0.348)
countycounty54 0.379
(0.347)
countycounty55 −0.587+
(0.348)
countycounty56 −0.057
(0.347)
countycounty57 0.483
(0.347)
countycounty58 −0.218
(0.347)
countycounty59 −0.200
(0.347)
countycounty60 0.811*
(0.348)
countycounty61 0.218
(0.348)
countycounty62 −0.499
(0.347)
countycounty63 0.510
(0.348)
countycounty64 −0.126
(0.347)
countycounty65 −0.207
(0.347)
countycounty66 0.163
(0.347)
countycounty67 −0.034
(0.347)
countycounty68 −0.288
(0.347)
countycounty69 0.939**
(0.347)
countycounty70 0.508
(0.347)
countycounty71 −0.593+
(0.347)
countycounty72 0.297
(0.348)
countycounty73 0.538
(0.348)
countycounty74 0.133
(0.348)
countycounty75 −0.016
(0.349)
countycounty76 −0.118
(0.347)
countycounty77 0.100
(0.348)
countycounty78 −0.432
(0.348)
countycounty79 0.364
(0.347)
countycounty80 0.361
(0.347)
countycounty81 −0.074
(0.347)
countycounty82 0.891*
(0.348)
countycounty83 −0.778*
(0.347)
countycounty84 −0.019
(0.348)
countycounty85 0.810*
(0.348)
countyANOKA 0.034
(0.393)
countyBECKER 0.688
(0.579)
countyBELTRAMI 0.712
(0.475)
countyBENTON 0.592
(0.535)
countyBIG STONE 0.672
(0.578)
countyBLUE EARTH 1.172**
(0.429)
countyBROWN 1.149*
(0.535)
countyCARLTON 0.162
(0.448)
countyCARVER 0.723
(0.489)
countyCASS 0.561
(0.508)
countyCHIPPEWA 0.890+
(0.535)
countyCHISAGO 0.198
(0.489)
countyCLAY 1.148**
(0.429)
countyCLEARWATER 0.497
(0.535)
countyCOOK −0.176
(0.655)
countyCOTTONWOOD 0.434
(0.536)
countyCROW WING 0.281
(0.437)
countyDAKOTA 0.498
(0.390)
countyDODGE 0.960+
(0.578)
countyDOUGLAS 0.893*
(0.455)
countyFARIBAULT −0.204
(0.488)
countyFILLMORE 0.559
(0.655)
countyFREEBORN 1.261**
(0.455)
countyGOODHUE 1.110**
(0.429)
countyHENNEPIN 0.520
(0.385)
countyHOUSTON 0.933+
(0.488)
countyHUBBARD 0.401
(0.508)
countyISANTI 0.215
(0.578)
countyITASCA 0.085
(0.442)
countyJACKSON 1.180*
(0.508)
countyKANABEC 0.396
(0.535)
countyKANDIYOHI 1.221*
(0.535)
countyKITTSON 0.750
(0.579)
countyKOOCHICHING −0.021
(0.475)
countyLAC QUI PARLE 2.118**
(0.655)
countyLAKE −0.438
(0.455)
countyLAKE OF THE WOODS 1.027+
(0.535)
countyLE SUEUR 0.908+
(0.507)
countyLINCOLN 1.475**
(0.535)
countyLYON 1.127*
(0.463)
countyMAHNOMEN 0.520
(0.846)
countyMARSHALL 0.762+
(0.455)
countyMARTIN 0.200
(0.474)
countyMCLEOD 0.455
(0.433)
countyMEEKER 0.374
(0.508)
countyMILLE LACS 0.043
(0.655)
countyMORRISON 0.308
(0.455)
countyMOWER 0.862*
(0.433)
countyMURRAY 1.653+
(0.846)
countyNICOLLET 1.324*
(0.535)
countyNOBLES 1.087+
(0.578)
countyNORMAN 0.410
(0.578)
countyOLMSTED 0.466
(0.410)
countyOTTER TAIL 0.777+
(0.463)
countyPENNINGTON 0.261
(0.579)
countyPINE −0.078
(0.488)
countyPIPESTONE 1.020+
(0.535)
countyPOLK 0.881
(0.535)
countyPOPE 0.439
(0.655)
countyRAMSEY 0.318
(0.401)
countyREDWOOD 1.142*
(0.507)
countyRENVILLE 0.830
(0.578)
countyRICE 1.007*
(0.442)
countyROCK 0.459
(0.655)
countyROSEAU 0.825+
(0.430)
countySCOTT 0.963*
(0.433)
countySHERBURNE 0.249
(0.464)
countySIBLEY 0.402
(0.535)
countyST LOUIS 0.027
(0.385)
countySTEARNS 0.651
(0.407)
countySTEELE 0.739+
(0.448)
countySTEVENS 0.951
(0.655)
countySWIFT 0.146
(0.535)
countyTODD 0.883
(0.578)
countyTRAVERSE 1.168*
(0.535)
countyWABASHA 0.981*
(0.474)
countyWADENA 0.445
(0.508)
countyWASECA −0.226
(0.535)
countyWASHINGTON 0.489
(0.394)
countyWATONWAN 1.869**
(0.579)
countyWILKIN 1.389
(0.846)
countyWINONA 0.782+
(0.433)
countyWRIGHT 0.805+
(0.433)
countyYELLOW MEDICINE 0.346
(0.655)
SD (Intercept county) 0.376 0.349
SD (first_floor county) 0.380 0.344
Cor (Intercept~first_floor county) −0.328 −0.337
SD (Observations) 0.734 0.746
Num.Obs. 935 919 935 919 935 919
R2 0.543 0.287 0.392 0.072
R2 Adj. 0.497 0.214 0.391 0.071
R2 Marg. 0.387 0.086
R2 Cond. 0.595 0.257
AIC 2353.8 2178.6 2453.6 2253.0 2308.2 2180.3
BIC 2775.0 2598.2 2468.1 2267.5 2337.2 2209.3
ICC 0.3 0.2
Log.Lik. −1089.911 −1002.310 −1223.776 −1123.512
F 11.872 3.945 600.496 70.914
RMSE 0.78 0.72 0.90 0.82 0.69 0.72
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001
#Visualisations

#table1
df$county <- as.factor(df$county)

table1(~ log.radon | county, transpose = TRUE, data=df) #inconvenient but somewhat works
log.radon
county01
(N=11)
:
Mean (SD): 1.09 (2.04)
Median [Min, Max]: 1.47 [-2.23, 3.30]
county02
(N=11)
:
Mean (SD): 1.34 (1.58)
Median [Min, Max]: 1.29 [-1.49, 3.98]
county03
(N=11)
:
Mean (SD): 0.865 (1.01)
Median [Min, Max]: 1.33 [-1.00, 2.04]
county04
(N=11)
:
Mean (SD): 1.08 (1.27)
Median [Min, Max]: 1.28 [-1.16, 3.04]
county05
(N=11)
:
Mean (SD): 1.87 (1.45)
Median [Min, Max]: 1.68 [-0.145, 4.26]
county06
(N=11)
:
Mean (SD): 1.64 (0.888)
Median [Min, Max]: 1.81 [0.427, 2.93]
county07
(N=11)
:
Mean (SD): 2.26 (1.86)
Median [Min, Max]: 2.71 [-1.46, 4.50]
county08
(N=11)
:
Mean (SD): 1.42 (1.04)
Median [Min, Max]: 1.61 [-0.802, 3.02]
county09
(N=11)
:
Mean (SD): 1.54 (1.23)
Median [Min, Max]: 1.72 [-0.0601, 3.34]
county10
(N=11)
:
Mean (SD): 0.884 (0.623)
Median [Min, Max]: 0.912 [-0.210, 1.96]
county11
(N=11)
:
Mean (SD): 1.20 (0.820)
Median [Min, Max]: 1.16 [-0.479, 2.31]
county12
(N=11)
:
Mean (SD): 1.22 (0.853)
Median [Min, Max]: 1.37 [0.00574, 2.30]
county13
(N=11)
:
Mean (SD): 1.95 (0.645)
Median [Min, Max]: 1.89 [1.12, 2.99]
county14
(N=11)
:
Mean (SD): 1.43 (1.39)
Median [Min, Max]: 1.37 [-0.805, 3.49]
county15
(N=11)
:
Mean (SD): 1.44 (1.43)
Median [Min, Max]: 1.73 [-1.88, 3.45]
county16
(N=11)
:
Mean (SD): 1.64 (1.47)
Median [Min, Max]: 1.31 [-0.380, 4.16]
county17
(N=11)
:
Mean (SD): 1.15 (0.693)
Median [Min, Max]: 1.34 [-0.0434, 2.35]
county18
(N=11)
:
Mean (SD): 1.75 (0.755)
Median [Min, Max]: 1.63 [0.931, 3.15]
county19
(N=11)
:
Mean (SD): 2.49 (1.23)
Median [Min, Max]: 2.14 [1.24, 5.31]
county20
(N=11)
:
Mean (SD): 1.72 (0.870)
Median [Min, Max]: 1.65 [0.297, 3.14]
county21
(N=11)
:
Mean (SD): 1.66 (0.753)
Median [Min, Max]: 1.62 [0.399, 2.94]
county22
(N=11)
:
Mean (SD): 1.95 (0.640)
Median [Min, Max]: 1.84 [0.945, 3.02]
county23
(N=11)
:
Mean (SD): 1.87 (1.06)
Median [Min, Max]: 1.99 [-0.381, 3.17]
county24
(N=11)
:
Mean (SD): 1.48 (1.08)
Median [Min, Max]: 1.85 [-0.0450, 2.96]
county25
(N=11)
:
Mean (SD): 0.899 (1.06)
Median [Min, Max]: 1.13 [-1.24, 2.30]
county26
(N=11)
:
Mean (SD): 0.858 (0.939)
Median [Min, Max]: 0.788 [-0.369, 2.95]
county27
(N=11)
:
Mean (SD): 1.51 (1.19)
Median [Min, Max]: 1.51 [-0.584, 3.32]
county28
(N=11)
:
Mean (SD): 0.829 (0.787)
Median [Min, Max]: 0.903 [-0.344, 2.15]
county29
(N=11)
:
Mean (SD): 1.32 (0.737)
Median [Min, Max]: 1.07 [0.337, 2.44]
county30
(N=11)
:
Mean (SD): 1.40 (0.522)
Median [Min, Max]: 1.42 [0.661, 2.60]
county31
(N=11)
:
Mean (SD): 0.759 (0.872)
Median [Min, Max]: 0.857 [-0.637, 1.73]
county32
(N=11)
:
Mean (SD): 2.12 (1.07)
Median [Min, Max]: 1.92 [0.611, 4.67]
county33
(N=11)
:
Mean (SD): 1.39 (0.806)
Median [Min, Max]: 1.37 [0.407, 2.80]
county34
(N=11)
:
Mean (SD): 1.06 (0.734)
Median [Min, Max]: 1.04 [-0.170, 2.22]
county35
(N=11)
:
Mean (SD): 1.51 (1.04)
Median [Min, Max]: 1.04 [0.409, 3.28]
county36
(N=11)
:
Mean (SD): 2.51 (0.535)
Median [Min, Max]: 2.66 [1.56, 3.29]
county37
(N=11)
:
Mean (SD): 0.943 (1.27)
Median [Min, Max]: 1.08 [-0.529, 3.79]
county38
(N=11)
:
Mean (SD): 0.943 (0.831)
Median [Min, Max]: 0.643 [-0.396, 1.87]
county39
(N=11)
:
Mean (SD): 1.86 (0.996)
Median [Min, Max]: 1.65 [0.703, 4.05]
county40
(N=11)
:
Mean (SD): 1.54 (0.876)
Median [Min, Max]: 1.50 [-0.505, 2.80]
county41
(N=11)
:
Mean (SD): 1.49 (1.14)
Median [Min, Max]: 1.11 [0.169, 3.54]
county42
(N=11)
:
Mean (SD): 1.19 (0.789)
Median [Min, Max]: 0.968 [0.279, 2.58]
county43
(N=11)
:
Mean (SD): 1.87 (1.04)
Median [Min, Max]: 1.86 [-0.0619, 3.35]
county44
(N=11)
:
Mean (SD): 2.70 (0.581)
Median [Min, Max]: 2.66 [1.87, 3.56]
county45
(N=11)
:
Mean (SD): 1.62 (1.07)
Median [Min, Max]: 1.55 [-0.478, 3.65]
county46
(N=11)
:
Mean (SD): 1.49 (1.35)
Median [Min, Max]: 1.40 [-0.711, 3.47]
county47
(N=11)
:
Mean (SD): 1.20 (0.818)
Median [Min, Max]: 1.19 [-0.568, 2.26]
county48
(N=11)
:
Mean (SD): 0.917 (1.03)
Median [Min, Max]: 1.02 [-1.50, 2.64]
county49
(N=11)
:
Mean (SD): 1.69 (0.658)
Median [Min, Max]: 1.90 [0.263, 2.54]
county50
(N=11)
:
Mean (SD): 0.968 (1.40)
Median [Min, Max]: 1.40 [-1.68, 3.43]
county51
(N=11)
:
Mean (SD): 0.914 (1.29)
Median [Min, Max]: 1.43 [-1.65, 2.02]
county52
(N=11)
:
Mean (SD): 2.10 (1.10)
Median [Min, Max]: 1.69 [0.757, 3.66]
county53
(N=11)
:
Mean (SD): 2.07 (0.979)
Median [Min, Max]: 2.25 [0.573, 3.24]
county54
(N=11)
:
Mean (SD): 1.50 (0.884)
Median [Min, Max]: 1.86 [0.0468, 2.64]
county55
(N=11)
:
Mean (SD): 0.940 (1.02)
Median [Min, Max]: 0.932 [-1.06, 2.54]
county56
(N=11)
:
Mean (SD): 1.26 (0.639)
Median [Min, Max]: 1.34 [0.310, 2.22]
county57
(N=11)
:
Mean (SD): 1.47 (1.00)
Median [Min, Max]: 1.79 [-0.650, 2.70]
county58
(N=11)
:
Mean (SD): 0.789 (1.06)
Median [Min, Max]: 1.41 [-0.860, 1.93]
county59
(N=11)
:
Mean (SD): 0.889 (0.915)
Median [Min, Max]: 1.01 [-0.245, 2.66]
county60
(N=11)
:
Mean (SD): 2.47 (1.43)
Median [Min, Max]: 2.28 [0.165, 4.38]
county61
(N=11)
:
Mean (SD): 1.63 (1.06)
Median [Min, Max]: 1.46 [-0.0259, 3.19]
county62
(N=11)
:
Mean (SD): 0.623 (1.33)
Median [Min, Max]: 0.437 [-1.04, 3.02]
county63
(N=11)
:
Mean (SD): 1.25 (0.763)
Median [Min, Max]: 1.27 [-0.406, 2.53]
county64
(N=11)
:
Mean (SD): 1.11 (1.34)
Median [Min, Max]: 1.18 [-1.61, 3.01]
county65
(N=11)
:
Mean (SD): 0.874 (0.778)
Median [Min, Max]: 0.735 [-0.316, 2.64]
county66
(N=11)
:
Mean (SD): 1.34 (1.14)
Median [Min, Max]: 1.36 [-0.351, 3.76]
county67
(N=11)
:
Mean (SD): 1.10 (0.837)
Median [Min, Max]: 1.42 [-0.266, 2.20]
county68
(N=11)
:
Mean (SD): 0.954 (0.636)
Median [Min, Max]: 1.16 [-0.151, 1.87]
county69
(N=11)
:
Mean (SD): 2.15 (0.973)
Median [Min, Max]: 1.79 [1.10, 3.85]
county70
(N=11)
:
Mean (SD): 1.46 (1.47)
Median [Min, Max]: 1.03 [-0.624, 3.87]
county71
(N=11)
:
Mean (SD): 0.456 (0.815)
Median [Min, Max]: 0.518 [-1.01, 1.45]
county72
(N=11)
:
Mean (SD): 1.86 (1.18)
Median [Min, Max]: 1.79 [0.288, 3.90]
county73
(N=11)
:
Mean (SD): 2.25 (1.17)
Median [Min, Max]: 2.02 [0.558, 4.33]
county74
(N=11)
:
Mean (SD): 1.49 (0.580)
Median [Min, Max]: 1.38 [0.704, 2.70]
county75
(N=11)
:
Mean (SD): 0.261 (1.24)
Median [Min, Max]: 0.762 [-1.44, 2.31]
county76
(N=11)
:
Mean (SD): 1.02 (1.77)
Median [Min, Max]: 1.22 [-1.82, 4.07]
county77
(N=11)
:
Mean (SD): 1.82 (0.662)
Median [Min, Max]: 2.02 [0.733, 2.74]
county78
(N=11)
:
Mean (SD): 1.26 (0.664)
Median [Min, Max]: 1.30 [0.302, 2.18]
county79
(N=11)
:
Mean (SD): 1.34 (1.41)
Median [Min, Max]: 1.50 [-1.74, 2.93]
county80
(N=11)
:
Mean (SD): 1.33 (1.15)
Median [Min, Max]: 1.53 [-1.04, 3.45]
county81
(N=11)
:
Mean (SD): 0.932 (1.83)
Median [Min, Max]: 0.251 [-1.62, 4.38]
county82
(N=11)
:
Mean (SD): 2.31 (0.850)
Median [Min, Max]: 2.31 [1.16, 3.76]
county83
(N=11)
:
Mean (SD): 0.558 (1.10)
Median [Min, Max]: 0.354 [-0.644, 2.78]
county84
(N=11)
:
Mean (SD): 1.70 (0.581)
Median [Min, Max]: 1.74 [0.556, 2.52]
county85
(N=11)
:
Mean (SD): 1.65 (1.52)
Median [Min, Max]: 1.97 [-0.658, 3.84]
Overall
(N=935)
:
Mean (SD): 1.42 (1.15)
Median [Min, Max]: 1.41 [-2.23, 5.31]
#ggpairs
ggpairs(df, title = "Radon levels in houses in Minnesota, United States", 
        upper = list(combo = "box_no_facet", discrete = "facetbar",  
                na = "na"),
        lower = list(combo = "dot_no_facet", discrete = "colbar",
                  na = "na"),
         columns = c("log.radon", "first_floor"), 
        )

#Compare to real radon data
ggpairs(radon_mn, title = "Radon levels in houses in Minnesota, United States", 
        upper = list(combo = "box_no_facet", discrete = "facetbar",  
                na = "na"),
        lower = list(combo = "dot_no_facet", discrete = "colbar",
                  na = "na"),
         columns = c("log.radon", "first_floor"), 
        )

#Caterpillar plot simulated

clusters <- df %>%
  pull(county) %>%
  unique()

predict_y <- mdl_multilevel_art %>%
  ranef() %>%
  augment() %>%
  as_tibble() %>%
  filter(variable == "(Intercept)") %>%
  arrange(estimate) %>%
  mutate(county = fct_inorder(level)) 

predict_y %>%
  ggplot(aes(xmin = lb, xmax = ub, y = county, x = estimate)) + 
    geom_pointrange( ) + 
    labs(x = "Estimate of the intercept (Y_hat when X=0)", y = NULL)

#Compare to real caterpillar plot
clusters <- radon_mn %>%
  pull(county) %>%
  unique()

predict_y <- mdl_multilevel %>%
  ranef() %>%
  augment() %>%
  as_tibble() %>%
  filter(variable == "(Intercept)") %>%
  arrange(estimate) %>%
  mutate(county = fct_inorder(level)) 

predict_y %>%
  ggplot(aes(xmin = lb, xmax = ub, y = county, x = estimate)) + 
    geom_pointrange( ) + 
    labs(x = "Estimate of the intercept (Y_hat when X=0)", y = NULL)

## Lattice plots
predictions(mdl_multilevel_art) %>% 
  ggplot(aes(first_floor, log.radon, color = county)) + 
  geom_point() + 
  geom_line(aes(y = predict(mdl_multilevel_art))) + 
  facet_wrap(~ county) +
  theme(legend.position = "none")

#Compare to real data
predictions(mdl_multilevel) %>% 
  ggplot(aes(x = first_floor, y = log.radon)) + 
  geom_point() + 
  geom_line(aes(y = predict(mdl_multilevel))) + 
  facet_wrap(~ county) +
  theme(legend.position = "none")
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?

##Spaghetti plots
predictions(mdl_multilevel_art) %>% 
  ggplot(aes(first_floor, log.radon, color = county)) + 
  geom_point() + 
  geom_line(aes(y = predict(mdl_multilevel_art))) + 
  theme(legend.position = "none")

#Compare to real data
predictions(mdl_multilevel) %>% 
  ggplot(aes(first_floor, log.radon, color = county, show.legend = FALSE)) + 
  geom_point() + 
  geom_line(aes(y = predict(mdl_multilevel))) +
  theme(legend.position = "none")

Answer The multilevel model made based on the artificial data resembles the multilevel model based on the real radon data, all parameters are very similar due to these being used as input for the simulated data. The same goes for the complete pooled model, One difference is that all ‘counties’ in the simulated data have the same number of measurements (the mean of measurements per county in the real dat), while this varies in the real data. Another difference that becomes apparent in the table1 and ggpairs is the layout of the data; while the real data has a factor variable for whether the data was collected on the basement or first floor, the simulated data has a continuous variable first_floor that resembles the difference in measurement between a first and second floor, as if each measurement happened on both floors. This is also visible in the lattice and spaghetti plots, although they are tiny due to the amount of clusters.

In the caterpillar plot, the artificial data seems to have a greater between-cluster variance for the estimate of the intercept when the X = 0, especially on the upper tail. Of course, the confidence intervals in the real data are also generally wider and more variable due to the varying number of observations per cluster.