# 1. load the appropriate libraries
library(tidyverse)
library(broom)
library(GGally)
library(car)
library(easystats)
library(datawizard)
library(marginaleffects)
library(modelsummary)
library(table1)

# 2. use the read_rds file to read the dataset
natality <- read_rds("data/natality.rds")

Exercise 1

Question: Use the table1 package to create a table with appropriate descriptive information about the data set. Use the examples provided in the following vignette to help you build a table. Feel free to try a different table with other variables. What do you notice from this table? What research questions might it raise?

# Write your code here
natality$CIG_REC <- factor(natality$CIG_REC, 
         levels=c("No","Yes"),
         labels=c("Non-Smoker","Smoker"),
          )
# How to stop it from dying if run again?

natality$risks <- factor(natality$risks)
natality$MRACEHISP <- factor(natality$MRACEHISP)
natality$DMAR <- factor(natality$DMAR)
natality$MEDUC <- factor(natality$MEDUC)
natality$PRIORLOVE <- factor(natality$PRIORLIVE)
natality$PRIORDEAD <- factor(natality$PRIORDEAD)

label(natality$risks) <- "Risk Factors Reported"
label(natality$MRACEHISP) <- "Mother Race/Hispanic Origin"
label(natality$DMAR) <- "Marital Status"
label(natality$MEDUC) <- "Mother Education"
label(natality$PRIORLOVE) <- "Prior births (living)"
label(natality$PRIORDEAD) <- "Prior births (dead)"


table1(~ DBWT + risks + MAGER + MRACEHISP + DMAR + MEDUC + PRIORLIVE + PRIORDEAD + BMI | CIG_REC, data=natality, overall = FALSE)
Non-Smoker
(N=1564)
Smoker
(N=124)
Birth Weight (g)
Mean (SD) 3250 (601) 3070 (597)
Median [Min, Max] 3290 [369, 5880] 3090 [630, 4220]
Risk Factors Reported
No 1088 (69.6%) 84 (67.7%)
Yes 476 (30.4%) 40 (32.3%)
Mother Age
Mean (SD) 29.0 (5.79) 27.8 (5.79)
Median [Min, Max] 29.0 [15.0, 49.0] 28.0 [17.0, 42.0]
Mother Race/Hispanic Origin
NH White 844 (54.0%) 94 (75.8%)
NH Black 266 (17.0%) 14 (11.3%)
NH Other 125 (8.0%) 10 (8.1%)
Hispanic 329 (21.0%) 6 (4.8%)
Marital Status
Married 1017 (65.0%) 40 (32.3%)
Unmarried 547 (35.0%) 84 (67.7%)
Mother Education
lower 177 (11.3%) 34 (27.4%)
HS 377 (24.1%) 45 (36.3%)
Some college 437 (27.9%) 37 (29.8%)
Uni 573 (36.6%) 8 (6.5%)
PRIORLIVE
0 601 (38.4%) 38 (30.6%)
1 516 (33.0%) 41 (33.1%)
2 265 (16.9%) 17 (13.7%)
3 93 (5.9%) 17 (13.7%)
4+ 89 (5.7%) 11 (8.9%)
Prior births (dead)
0 1551 (99.2%) 123 (99.2%)
1+ 13 (0.8%) 1 (0.8%)
Mother BMI
Mean (SD) 26.9 (6.32) 27.3 (6.42)
Median [Min, Max] 25.6 [15.6, 58.4] 26.3 [16.5, 50.1]

Answer: Comparing the smokers and non-smokers there seems to be a slightly lower birth weight in the smoking group. There also seems to be a much larger proportion of Hispanic mothers in the non-smoking group. The education level appears to be higher in the non-smoking group. I think the most interesting research question here would relate to the differences in education level as it shows the most consistent and largest difference.

Exercise 2

Question: Use the ggpairs function to explore the association between the different variables. Try to replicate the figure below, or create your own variation. What do you see in the figure? What new information does it provide? What are the advantages/disadvantages when comparing table1 to ggpairs?

# Write your code here
pm <- ggpairs(natality, 
              aes(color = CIG_REC), 
              columns = c("DBWT", "risks", "MAGER", "DMAR", "BMI"), 
              columnLabels = c("Birth Weight (g)", "Risk Factors Reported", "Mothers Age", "Marital Status", "Mother BMI") ,  
  lower = list(
    continuous = "cor",
    combo = "facethist",
    mapping = aes(color = CIG_REC)
  ),
  upper = list(
    continuous = "density",
    combo = "facethist",
    discrete = "colbar",
    mapping = aes(color = CIG_REC)
  ),
  diag = list(
    continuous = wrap("densityDiag", alpha = 0.5, color = FALSE),
    discrete = "densityDiag", 
    mapping = aes(color = CIG_REC)))
pm

Answer: This creates a graphical representation of the information given in table1. Furthermore it provides additional information like the shapes of distributions and correlations between variables. I think advantages of the table1 function are that it is easier to read and create, while advantages of the ggpairs function are providing more extensive information and more customization options.

Exercise 3

Question: Fit four linear models, each nested within the other: the null model, the unadjusted model, the full model and the optimal model. Use the step function find the optimal model using the stepwise method. Then use anova to compare the four models. What is your conclusion? Now compare your models using modelsummary function. What does the number in the (brackets) mean? How can you identify the optimal model just by looking at the R2 and the AIC?

# Write your code here
M.NULL <- lm(DBWT ~ 1, natality)
M.UNADJUSTED <- lm(DBWT ~ CIG_REC, natality)
# The dot represents all variables except the outcome DBWT
M.FULL <- lm(DBWT ~ ., natality)  

# Finding the optimal model
step(M.NULL,
     scope = list(upper = M.FULL),
     direction="both",
     data=natality)
## Start:  AIC=21609.55
## DBWT ~ 1
## 
##             Df Sum of Sq       RSS   AIC
## + DMAR       1  28672236 583166851 21530
## + MRACEHISP  3  28557357 583281730 21535
## + PRIORLIVE  4   7485192 604353895 21597
## + PRIORLOVE  4   7485192 604353895 21597
## + MEDUC      3   5189885 606649203 21601
## + CIG_REC    1   3685187 608153901 21601
## + risks      1   3277949 608561138 21602
## + BMI        1   3170730 608668358 21603
## + MAGER      1   2941408 608897679 21603
## + PRIORDEAD  1    849628 610989460 21609
## <none>                   611839087 21610
## 
## Step:  AIC=21530.53
## DBWT ~ DMAR
## 
##             Df Sum of Sq       RSS   AIC
## + MRACEHISP  3  15359037 567807814 21492
## + risks      1   4395289 578771562 21520
## + BMI        1   3607980 579558871 21522
## + PRIORLIVE  4   4500359 578666492 21526
## + PRIORLOVE  4   4500359 578666492 21526
## + CIG_REC    1    978350 582188501 21530
## + PRIORDEAD  1    818812 582348039 21530
## <none>                   583166851 21530
## + MAGER      1     82475 583084376 21532
## + MEDUC      3    313468 582853384 21536
## - DMAR       1  28672236 611839087 21610
## 
## Step:  AIC=21491.48
## DBWT ~ DMAR + MRACEHISP
## 
##             Df Sum of Sq       RSS   AIC
## + BMI        1   4532441 563275373 21480
## + risks      1   3924653 563883161 21482
## + CIG_REC    1   2181695 565626119 21487
## + PRIORLIVE  4   3880005 563927809 21488
## + PRIORLOVE  4   3880005 563927809 21488
## + PRIORDEAD  1    846700 566961114 21491
## <none>                   567807814 21492
## + MAGER      1     52434 567755381 21493
## + MEDUC      3     98014 567709800 21497
## - MRACEHISP  3  15359037 583166851 21530
## - DMAR       1  15473916 583281730 21535
## 
## Step:  AIC=21479.95
## DBWT ~ DMAR + MRACEHISP + BMI
## 
##             Df Sum of Sq       RSS   AIC
## + risks      1   6059709 557215664 21464
## + CIG_REC    1   2362075 560913299 21475
## + PRIORLIVE  4   3457999 559817375 21478
## + PRIORLOVE  4   3457999 559817375 21478
## + PRIORDEAD  1    896345 562379028 21479
## <none>                   563275373 21480
## + MAGER      1    125890 563149483 21482
## + MEDUC      3    115009 563160364 21486
## - BMI        1   4532441 567807814 21492
## - MRACEHISP  3  16283498 579558871 21522
## - DMAR       1  15325756 578601129 21523
## 
## Step:  AIC=21463.69
## DBWT ~ DMAR + MRACEHISP + BMI + risks
## 
##             Df Sum of Sq       RSS   AIC
## + PRIORLIVE  4   5580134 551635530 21455
## + PRIORLOVE  4   5580134 551635530 21455
## + CIG_REC    1   2199370 555016294 21459
## + PRIORDEAD  1   1025923 556189741 21463
## <none>                   557215664 21464
## + MAGER      1     22588 557193076 21466
## + MEDUC      3     69675 557145989 21470
## - risks      1   6059709 563275373 21480
## - BMI        1   6667497 563883161 21482
## - MRACEHISP  3  15921403 573137067 21505
## - DMAR       1  16431163 573646827 21511
## 
## Step:  AIC=21454.7
## DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE
## 
##             Df Sum of Sq       RSS   AIC
## + CIG_REC    1   2707991 548927539 21448
## + PRIORDEAD  1    921529 550714001 21454
## <none>                   551635530 21455
## + MAGER      1    280671 551354859 21456
## + MEDUC      3    173640 551461890 21460
## - PRIORLIVE  4   5580134 557215664 21464
## - BMI        1   6486820 558122350 21472
## - risks      1   8181845 559817375 21478
## - MRACEHISP  3  15145908 566781438 21494
## - DMAR       1  14456460 566091990 21496
## 
## Step:  AIC=21448.4
## DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC
## 
##             Df Sum of Sq       RSS   AIC
## + PRIORDEAD  1    922493 548005046 21448
## <none>                   548927539 21448
## + MAGER      1    337056 548590483 21449
## + MEDUC      3     75431 548852108 21454
## - CIG_REC    1   2707991 551635530 21455
## - PRIORLIVE  4   6088755 555016294 21459
## - BMI        1   6662694 555590232 21467
## - risks      1   8131760 557059299 21471
## - DMAR       1  10955889 559883427 21480
## - MRACEHISP  3  16576572 565504111 21493
## 
## Step:  AIC=21447.56
## DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + 
##     PRIORDEAD
## 
##             Df Sum of Sq       RSS   AIC
## <none>                   548005046 21448
## - PRIORDEAD  1    922493 548927539 21448
## + MAGER      1    361028 547644018 21448
## + MEDUC      3     82260 547922786 21453
## - CIG_REC    1   2708955 550714001 21454
## - PRIORLIVE  4   5984714 553989760 21458
## - BMI        1   6749558 554754604 21466
## - risks      1   8234365 556239411 21471
## - DMAR       1  10970232 558975278 21479
## - MRACEHISP  3  16594210 564599256 21492
## 
## Call:
## lm(formula = DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + 
##     CIG_REC + PRIORDEAD, data = natality)
## 
## Coefficients:
##       (Intercept)      DMARUnmarried  MRACEHISPNH Black  MRACEHISPNH Other  
##           3080.56            -184.27            -292.14            -121.70  
## MRACEHISPHispanic                BMI           risksYes         PRIORLIVE1  
##            -74.49              10.26            -158.81             130.69  
##        PRIORLIVE2         PRIORLIVE3        PRIORLIVE4+      CIG_RECSmoker  
##            107.17             138.78             131.95            -160.08  
##       PRIORDEAD1+  
##            258.43
M.OPT <- lm(DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + 
    PRIORDEAD, natality)

anova(M.NULL, M.UNADJUSTED, M.OPT, M.FULL, test="Chisq")
## Analysis of Variance Table
## 
## Model 1: DBWT ~ 1
## Model 2: DBWT ~ CIG_REC
## Model 3: DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + 
##     PRIORDEAD
## Model 4: DBWT ~ CIG_REC + risks + MAGER + MRACEHISP + DMAR + MEDUC + PRIORLIVE + 
##     PRIORDEAD + BMI + PRIORLOVE
##   Res.Df       RSS Df Sum of Sq  Pr(>Chi)    
## 1   1687 611839087                           
## 2   1686 608153901  1   3685187 0.0007966 ***
## 3   1675 548005046 11  60148855 < 2.2e-16 ***
## 4   1671 547416336  4    588710 0.7730223    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Displaying the four models by each other
modelsummary(
  list(
    null = M.NULL, 
    unadjasted = M.UNADJUSTED, 
    full = M.FULL, 
    opt = M.OPT
    ), 
  stars = TRUE
  )
null unadjasted full opt
(Intercept) 3234.746*** 3247.903*** 3162.373*** 3080.559***
(14.658) (15.187) (107.021) (64.625)
CIG_RECSmoker −179.096** −156.593** −160.083**
(56.032) (56.325) (55.632)
risksYes −152.902*** −158.808***
(32.055) (31.655)
MAGER −3.836
(3.085)
MRACEHISPNH Black −290.175*** −292.140***
(41.829) (41.690)
MRACEHISPNH Other −120.774* −121.695*
(52.960) (52.796)
MRACEHISPHispanic −72.464+ −74.492+
(39.120) (38.075)
DMARUnmarried −189.782*** −184.275***
(35.084) (31.823)
MEDUCHS 8.448
(49.909)
MEDUCSome college −0.240
(50.838)
MEDUCUni 31.610
(56.902)
PRIORLIVE1 140.483*** 130.686***
(34.725) (33.814)
PRIORLIVE2 123.385** 107.170*
(43.880) (41.746)
PRIORLIVE3 161.298* 138.776*
(63.149) (59.972)
PRIORLIVE4+ 162.508* 131.949*
(67.562) (62.333)
PRIORDEAD1+ 265.467+ 258.434+
(154.184) (153.905)
BMI 10.493*** 10.261***
(2.277) (2.259)
Num.Obs. 1688 1688 1688 1688
R2 0.000 0.006 0.105 0.104
R2 Adj. 0.000 0.005 0.097 0.098
AIC 26401.9 26393.7 26246.1 26239.9
BIC 26412.7 26410.0 26343.8 26315.9
Log.Lik. −13198.942 −13193.843 −13105.039 −13105.946
F 10.217 16.259
RMSE 602.05 600.23 569.47 569.78
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Answer: After running the step function I selected the lowest AIC from the output to create the optimal model. Subsequently the anova output suggested that the residual sum of squares for this model is not significantly lower than the full model, while being significantly larger than the Null and Unadjusted model. The Model summary also provided me with the highest R2 and the lowest AIC for the optimal model, therefore suggesting it is indeed the best out of the four models. Lastly, the numbers in brackets represent the standard error for each predictor.

Exercise 4

Question: Center and scale all the continuous variables, and create a forest plot for the optimal model.

# Write your code here

# Scaling
natality.ctr <- natality |> 
  standardize(two_sd = TRUE)



# Fitting the model
M.OPT.ctr <- lm(
  DBWT ~ DMAR + MRACEHISP + BMI + 
    risks + PRIORLIVE + CIG_REC + 
    PRIORDEAD, 
  data = natality.ctr
  )

# creating a forest plot
M.OPT.ctr %>% 
  model_parameters() %>% 
  plot()

#How to label factors?

Answer: Im not sure what my job here was, but I believe I did it well!

Exercise 5

Question: How do the effect estimate of smoking, the standard error of its estimate, its 95% confidence interval, and its statistical significance change between the un-adjusted, optimal and full models? Please use the centered and scaled models to answer this question.

# Write your code here
M.UNADJUSTED.ctr <- lm(DBWT ~ CIG_REC, natality.ctr)
M.FULL.ctr <- lm(DBWT ~ ., natality.ctr) 

M.UNADJUSTED.ctr |> 
  tidy(conf.int = TRUE)
## # A tibble: 2 × 7
##   term          estimate std.error statistic p.value conf.low conf.high
##   <chr>            <dbl>     <dbl>     <dbl>   <dbl>    <dbl>     <dbl>
## 1 (Intercept)     0.0109    0.0126     0.866 0.386    -0.0138    0.0357
## 2 CIG_RECSmoker  -0.149     0.0465    -3.20  0.00142  -0.240    -0.0575
M.OPT.ctr |> 
  tidy(conf.int = TRUE)
## # A tibble: 13 × 7
##    term              estimate std.error statistic  p.value conf.low conf.high
##    <chr>                <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
##  1 (Intercept)         0.101     0.0238      4.25 2.24e- 5  0.0546   0.148   
##  2 DMARUnmarried      -0.153     0.0264     -5.79 8.36e- 9 -0.205   -0.101   
##  3 MRACEHISPNH Black  -0.243     0.0346     -7.01 3.51e-12 -0.310   -0.175   
##  4 MRACEHISPNH Other  -0.101     0.0438     -2.30 2.13e- 2 -0.187   -0.0151  
##  5 MRACEHISPHispanic  -0.0618    0.0316     -1.96 5.06e- 2 -0.124    0.000156
##  6 BMI                 0.108     0.0237      4.54 5.97e- 6  0.0612   0.154   
##  7 risksYes           -0.132     0.0263     -5.02 5.81e- 7 -0.183   -0.0803  
##  8 PRIORLIVE1          0.109     0.0281      3.86 1.15e- 4  0.0534   0.164   
##  9 PRIORLIVE2          0.0890    0.0347      2.57 1.03e- 2  0.0210   0.157   
## 10 PRIORLIVE3          0.115     0.0498      2.31 2.08e- 2  0.0176   0.213   
## 11 PRIORLIVE4+         0.110     0.0518      2.12 3.44e- 2  0.00805  0.211   
## 12 CIG_RECSmoker      -0.133     0.0462     -2.88 4.06e- 3 -0.224   -0.0423  
## 13 PRIORDEAD1+         0.215     0.128       1.68 9.33e- 2 -0.0361   0.465
M.FULL.ctr |> 
  tidy(conf.int = TRUE)
## # A tibble: 21 × 7
##    term               estimate std.error statistic  p.value conf.low conf.high
##    <chr>                 <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
##  1 (Intercept)        0.0823      0.0483   1.71    8.84e- 2  -0.0124   0.177  
##  2 CIG_RECSmoker     -0.130       0.0468  -2.78    5.49e- 3  -0.222   -0.0383 
##  3 risksYes          -0.127       0.0266  -4.77    2.00e- 6  -0.179   -0.0747 
##  4 MAGER             -0.0370      0.0297  -1.24    2.14e- 1  -0.0952   0.0213 
##  5 MRACEHISPNH Black -0.241       0.0347  -6.94    5.70e-12  -0.309   -0.173  
##  6 MRACEHISPNH Other -0.100       0.0440  -2.28    2.27e- 2  -0.187   -0.0140 
##  7 MRACEHISPHispanic -0.0602      0.0325  -1.85    6.41e- 2  -0.124    0.00354
##  8 DMARUnmarried     -0.158       0.0291  -5.41    7.24e- 8  -0.215   -0.100  
##  9 MEDUCHS            0.00701     0.0414   0.169   8.66e- 1  -0.0743   0.0883 
## 10 MEDUCSome college -0.000199    0.0422  -0.00472 9.96e- 1  -0.0830   0.0826 
## # ℹ 11 more rows
modelsummary(
  list(
    unadjasted = M.UNADJUSTED.ctr, 
    full = M.FULL.ctr, 
    opt = M.OPT.ctr
    ), 
  stars = TRUE
  )
unadjasted full opt
(Intercept) 0.011 0.082+ 0.101***
(0.013) (0.048) (0.024)
CIG_RECSmoker −0.149** −0.130** −0.133**
(0.047) (0.047) (0.046)
risksYes −0.127*** −0.132***
(0.027) (0.026)
MAGER −0.037
(0.030)
MRACEHISPNH Black −0.241*** −0.243***
(0.035) (0.035)
MRACEHISPNH Other −0.100* −0.101*
(0.044) (0.044)
MRACEHISPHispanic −0.060+ −0.062+
(0.032) (0.032)
DMARUnmarried −0.158*** −0.153***
(0.029) (0.026)
MEDUCHS 0.007
(0.041)
MEDUCSome college 0.000
(0.042)
MEDUCUni 0.026
(0.047)
PRIORLIVE1 0.117*** 0.109***
(0.029) (0.028)
PRIORLIVE2 0.102** 0.089*
(0.036) (0.035)
PRIORLIVE3 0.134* 0.115*
(0.052) (0.050)
PRIORLIVE4+ 0.135* 0.110*
(0.056) (0.052)
PRIORDEAD1+ 0.220+ 0.215+
(0.128) (0.128)
BMI 0.110*** 0.108***
(0.024) (0.024)
Num.Obs. 1688 1688 1688
R2 0.006 0.105 0.104
R2 Adj. 0.005 0.097 0.098
AIC 2445.1 2297.5 2291.3
BIC 2461.4 2395.2 2367.3
Log.Lik. −1219.537 −1130.732 −1131.640
F 10.217 16.259
RMSE 0.50 0.47 0.47
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001
#only print cigrec

Answer: The effect of smoking seems to be overestimated by the unadjusted, and slightly underestimated by the full model when compared to the optimal model. While significant for each of the models, the p value differs in orders of magnitude with the highest level being achieved by the optimal model. It also has the narrowest confidence interval.

Exercise 6

Question: Does the association between cigarette smoking during pregnancy and birth weight depend on mother’s education? Modify the FULL model appropriately to be able to answer this question. Use anova to test whether the model with the interaction is significantly better than the one without it. Regardless of statistical significance, create ONE of the dumbell plots shown below, illustrating the smoking effect at each level of mother’s education and estimate the cigarette smoking effect at each level of mother’s education. Hint: We will be using the marginaleffects package to create the plots.

# Write your code here
library(marginaleffects)
library(patchwork)

M.FULL_int.ctr <- lm(formula = DBWT ~ . + CIG_REC * MEDUC, data = natality.ctr)

predictions(M.FULL_int.ctr, 
            newdata = datagrid(
              model = M.FULL_int.ctr,
              MRACEHISP = c("NH White", "NH Black", "NH Other", "Hispanic"),
              MEDUC   = c("lower", "HS", "Some college", "Uni"),
              CIG_REC = c("Non-Smoker", "Smoker")
              )
            ) |> 
  as.data.frame() |> 
  mutate(DBWT = estimate)  |> 
  select(DBWT, MRACEHISP, CIG_REC, MEDUC) 
##            DBWT MRACEHISP    CIG_REC        MEDUC
## 1   0.062274688  NH White Non-Smoker        lower
## 2   0.044478085  NH White     Smoker        lower
## 3   0.088547793  NH White Non-Smoker           HS
## 4  -0.050146730  NH White     Smoker           HS
## 5   0.087773609  NH White Non-Smoker Some college
## 6  -0.132368083  NH White     Smoker Some college
## 7   0.106740302  NH White Non-Smoker          Uni
## 8   0.024046565  NH White     Smoker          Uni
## 9  -0.177128407  NH Black Non-Smoker        lower
## 10 -0.194925010  NH Black     Smoker        lower
## 11 -0.150855303  NH Black Non-Smoker           HS
## 12 -0.289549825  NH Black     Smoker           HS
## 13 -0.151629486  NH Black Non-Smoker Some college
## 14 -0.371771178  NH Black     Smoker Some college
## 15 -0.132662793  NH Black Non-Smoker          Uni
## 16 -0.215356530  NH Black     Smoker          Uni
## 17 -0.039972642  NH Other Non-Smoker        lower
## 18 -0.057769244  NH Other     Smoker        lower
## 19 -0.013699537  NH Other Non-Smoker           HS
## 20 -0.152394060  NH Other     Smoker           HS
## 21 -0.014473721  NH Other Non-Smoker Some college
## 22 -0.234615412  NH Other     Smoker Some college
## 23  0.004492972  NH Other Non-Smoker          Uni
## 24 -0.078200765  NH Other     Smoker          Uni
## 25  0.006155744  Hispanic Non-Smoker        lower
## 26 -0.011640859  Hispanic     Smoker        lower
## 27  0.032428848  Hispanic Non-Smoker           HS
## 28 -0.106265674  Hispanic     Smoker           HS
## 29  0.031654665  Hispanic Non-Smoker Some college
## 30 -0.188487027  Hispanic     Smoker Some college
## 31  0.050621358  Hispanic Non-Smoker          Uni
## 32 -0.032072379  Hispanic     Smoker          Uni
#NH White
plot_nh_white <- tribble(
  ~Education, ~No_Smoking, ~Smoking, 
  "Lower",    0.06227469,  0.04447809, 
  "HS",       0.08854779,  -0.05014673, 
  "Some College", 0.087773609, -0.132368083,
   "Uni", 0.106740302 ,    0.024046565 
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "No Smoking", y = No_Smoking, 
      xend = "Smoking", yend = Smoking, 
      color = Education
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "No Smoking", y = No_Smoking, color = Education), 
    size = 6
    ) + 
  geom_point(
    aes(x = "Smoking", y = Smoking, color = Education), 
    size = 6
    ) +
  labs (title = "NH White",y=NULL)

#NH Black
plot_nh_black <- tribble(
  ~Education, ~No_Smoking, ~Smoking, 
  "Lower",    -0.177128407,  -0.194925010, 
  "HS",       -0.150855303,  -0.289549825 , 
  "Some College", -0.151629486, -0.371771178,
   "Uni", -0.132662793 ,    -0.215356530 
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "No Smoking", y = No_Smoking, 
      xend = "Smoking", yend = Smoking, 
      color = Education
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "No Smoking", y = No_Smoking, color = Education), 
    size = 6
    ) + 
  geom_point(
    aes(x = "Smoking", y = Smoking, color = Education), 
    size = 6
    ) +
  labs (title = "NH Black",y=NULL)

#NH Other
plot_nh_other <- tribble(
  ~Education, ~No_Smoking, ~Smoking, 
  "Lower",    -0.039972642  ,  -0.057769244, 
  "HS",       -0.150855303,  -0.289549825 , 
  "Some College", -0.014473721, -0.234615412,
   "Uni", 0.004492972 ,    -0.078200765
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "No Smoking", y = No_Smoking, 
      xend = "Smoking", yend = Smoking, 
      color = Education
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "No Smoking", y = No_Smoking, color = Education), 
    size = 6
    ) + 
  geom_point(
    aes(x = "Smoking", y = Smoking, color = Education), 
    size = 6
    ) +
  labs (title = "NH Other",y=NULL)

#Hispanic
plot_hispanic <-tribble(
  ~Education, ~No_Smoking, ~Smoking, 
  "Lower",    0.006155744  ,  -0.011640859 , 
  "HS",       0.032428848,  -0.106265674 , 
  "Some College", 0.031654665, -0.188487027,
   "Uni", 0.050621358 ,    -0.032072379
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "No Smoking", y = No_Smoking, 
      xend = "Smoking", yend = Smoking, 
      color = Education
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "No Smoking", y = No_Smoking, color = Education), 
    size = 6
    ) + 
  geom_point(
    aes(x = "Smoking", y = Smoking, color = Education), 
    size = 6
    ) +
  labs (title = "Hispanic",y = NULL)


combined_plots <- plot_nh_white + plot_nh_black + plot_nh_other + plot_hispanic
combined_plots_with_label <- combined_plots +
  plot_layout(
    guides = "collect"
  ) +
  labs(y="Birth Weight")

combined_plots_with_label

# why are values different from example values?

Answer: I accidentally made all 4 and only realized when rereading the question to type this answer. Oopsie.

Exercise 7

Question: Does the association between mother’s BMI and birth-weight differ between mothers of different race/ethnicity? Modify the OPTIMAL model appropriately to be able to answer this question, using the dataset with the centered variables. Use anova to test whether the model with the interaction is significantly better than the one without it. Regardless of statistical significance, estimate the BMI effect at each level of mother’s race/ethnicity and plot the BMI effect at each level of mother’s race/ethnicity using a dumbell plot. Bonus: Provide a brief description, interpretation or reflection about what you see in the plot (e.g., what do you notice? what do you wonder?)

# Write your code here
M.OPT.INT.ctr <- lm(
  DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + BMI * MRACEHISP + PRIORDEAD, 
  data = natality.ctr
  )

predictions(M.OPT.INT.ctr, 
            newdata = datagrid(
              model = M.OPT.INT.ctr,
              MRACEHISP = c("NH White", "NH Black", "NH Other", "Hispanic"),
              BMI = c(mean(M.OPT.INT.ctr$BMI), mean(M.OPT.INT.ctr$BMI) + sd(M.OPT.INT.ctr$BMI))
              )
            ) |> 
  as.data.frame() |> 
  mutate(DBWT = estimate)  |> 
  select(DBWT, MRACEHISP, BMI) 
##   DBWT MRACEHISP BMI
## 1   NA  NH White  NA
## 2   NA  NH Black  NA
## 3   NA  NH Other  NA
## 4   NA  Hispanic  NA
tribble(
  ~Race, ~BMI, ~BMIsd, 
  "NH White",    0.10284377,  0.22283552, 
  "NH Black",       -0.13666489  ,  -0.06699297, 
   "NH Other",        0.01078647,         0.25114286, 
  "Hispanic",        0.04215825 ,          0.11641484
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "mean(BMI)", y = BMI, 
      xend = "mean(BMI) + sd", yend = BMIsd, 
      color = Race
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "mean(BMI)", y = BMI, color = Race), 
    size = 6
    ) + 
  geom_point(
    aes(x = "mean(BMI) + sd", y = BMIsd, color = Race), 
    size = 6
    ) +
  labs(y="Birth Weight")

anova(M.OPT.ctr, M.OPT.INT.ctr, test="Chisq")
## Analysis of Variance Table
## 
## Model 1: DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + 
##     PRIORDEAD
## Model 2: DBWT ~ DMAR + MRACEHISP + BMI + risks + PRIORLIVE + CIG_REC + 
##     BMI * MRACEHISP + PRIORDEAD
##   Res.Df    RSS Df Sum of Sq Pr(>Chi)
## 1   1675 377.75                      
## 2   1672 377.04  3   0.71163   0.3682

Answer: From this plot it looks like the effect of maternal BMI on birth weight is larger for the NH other group. While the other three slopes run relatively parallel with different intercepts, this slope is noticeably steeper. However, the anova suggests that this model is not significantly better than the model without interaction effects, therefore this likely is just a coincidental occurence within our sample. Or if there is an effect it is not large enough within this one group to outweight the absent interaction in the other three groups.

Exercise 8

Question: Does the association between mother’s BMI and birth-weight depend on mother’s age? Modify the FULL model appropriately to be able to answer this question, using the dataset with the centered variables. Use anova to test whether the model with the interaction is significantly better than the one without it. Regardless of statistical significance, estimate the BMI effect for mothers age 20, 30, and 40 years and make a plot illustrating the BMI effect at each of these ages. Bonus: Provide a brief description, interpretation or reflection about what you see in the plot (e.g., what do you notice? what do you wonder?)

# Write your code here
M.FULL.INT.ctr <- lm(formula = DBWT ~ . + BMI * MAGER, data = natality.ctr)

predictions(M.FULL.INT.ctr, 
            newdata = datagrid(
              model = M.FULL.INT.ctr,
              MAGER = c(20, 30, 40),
              BMI = c(mean(M.FULL.INT.ctr$BMI), mean(M.FULL.INT.ctr$BMI) + sd(M.FULL.INT.ctr$BMI))
              
              
              )
            ) |> 
  as.data.frame() |> 
  mutate(DBWT = estimate)  |> 
  select(DBWT, MAGER, BMI) 
##   DBWT MAGER BMI
## 1   NA    20  NA
## 2   NA    30  NA
## 3   NA    40  NA
tribble(
  ~Age, ~BMI, ~BMIsd, 
  "20",     -0.632467,  -1.007501 , 
  "30",       -1.002800   ,  -1.620317, 
   "40",         -1.373132,         -2.233134, 
  
  ) |> ggplot() + 
  geom_segment(
    aes(
      x = "mean(BMI)", y = BMI, 
      xend = "mean(BMI) + sd", yend = BMIsd, 
      color = Age
      ),
    linewidth = 2
    ) + 
  geom_point(
    aes(x = "mean(BMI)", y = BMI, color = Age), 
    size = 6
    ) + 
  geom_point(
    aes(x = "mean(BMI) + sd", y = BMIsd, color = Age), 
    size = 6
    )+
   labs(y="Birth Weight")

anova(M.FULL.ctr, M.FULL.INT.ctr, test="Chisq")
## Analysis of Variance Table
## 
## Model 1: DBWT ~ CIG_REC + risks + MAGER + MRACEHISP + DMAR + MEDUC + PRIORLIVE + 
##     PRIORDEAD + BMI + PRIORLOVE
## Model 2: DBWT ~ CIG_REC + risks + MAGER + MRACEHISP + DMAR + MEDUC + PRIORLIVE + 
##     PRIORDEAD + BMI + PRIORLOVE + BMI * MAGER
##   Res.Df    RSS Df Sum of Sq Pr(>Chi)
## 1   1671 377.34                      
## 2   1670 377.28  1  0.060384   0.6052

Answer: It looks like there might be a slight interaction effect between age and BMI with regards to birth weight. The older the mother, the lower the birthweight for a higher BMI. However, I am confused as the basic slopes seem to be inverted here, indicating lower birth weight for higher maternal BMI, while in the previous example there was an increase with increasing BMI. This matches the provided example but I still find it peculiar. Although, once again, the ANOVA didnt find a significant difference between the models when addidng the interaction effect, so I am not gonna lie awake at night about this.