-
Notifications
You must be signed in to change notification settings - Fork 11
/
Linear-models-overview.qmd
2262 lines (1590 loc) · 46.4 KB
/
Linear-models-overview.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
df-print: paged
---
# Linear (Gaussian) Models
---
{{< include shared-config.qmd >}}
---
:::{.callout-note}
This content is adapted from:
- @dobson4e, Chapters 2-6
- @dunn2018generalized, Chapters 2-3
- @vittinghoff2e, Chapter 4
There are numerous textbooks specifically for linear regression, including:
- @kutner2005applied: used for UCLA Biostatistics MS level linear models class
- @chatterjee2015regression: used for Stanford MS-level linear models class
- @seber2012linear: used for UCLA Biostatistics PhD level linear models class and UC Davis STA 108.
- @kleinbaum2014applied: same first author as @kleinbaum2010logistic and @kleinbaum2012survival
- @weisberg2005applied
- *Linear Models with R* [@Faraway2025-io]
:::
## Overview
### Why this course includes linear regression {.smaller}
:::{.fragment .fade-in-then-semi-out}
* This course is about *generalized linear models* (for non-Gaussian outcomes)
:::
:::{.fragment .fade-in-then-semi-out}
* UC Davis STA 108 ("Applied Statistical Methods: Regression Analysis") is a prerequisite for this course, so everyone here should have some understanding of linear regression already.
:::
:::{.fragment .fade-in}
* We will review linear regression to:
- make sure everyone is caught up
- to provide an epidemiological perspective on model interpretation.
:::
### Chapter overview
* @sec-understand-LMs: how to interpret linear regression models
* @sec-est-LMs: how to estimate linear regression models
* @sec-infer-LMs: how to quantify uncertainty about our estimates
* @sec-diagnose-LMs: how to tell if your model is insufficiently complex
## Understanding Gaussian Linear Regression Models {#sec-understand-LMs}
### Motivating example: birthweights and gestational age {.smaller}
Suppose we want to learn about the distributions of birthweights (*outcome* $Y$) for (human) babies born at different gestational ages (*covariate* $A$) and with different chromosomal sexes (*covariate* $S$) (@dobson4e Example 2.2.2).
::::: {.panel-tabset}
#### Data as table
```{r}
#| label: tbl-birthweight-data1
#| tbl-cap: "`birthweight` data (@dobson4e Example 2.2.2)"
library(dobson)
data("birthweight", package = "dobson")
birthweight |> knitr::kable()
```
#### Reshape data for graphing
```{r}
#| label: tbl-birthweight-data2
#| tbl-cap: "`birthweight` data reshaped"
bw =
birthweight |>
pivot_longer(
cols = everything(),
names_to = c("sex", ".value"),
names_sep = "s "
) |>
rename(age = `gestational age`) |>
mutate(
sex = sex |>
case_match(
"boy" ~ "male",
"girl" ~ "female") |>
factor(levels = c("female", "male")))
bw
```
#### Data as graph
```{r}
#| label: fig-plot-birthweight1
#| fig-cap: "`birthweight` data (@dobson4e Example 2.2.2)"
#| fig-height: 5
#| fig-width: 7
plot1 = bw |>
ggplot(aes(
x = age,
y = weight,
linetype = sex,
shape = sex,
col = sex)) +
theme_bw() +
xlab("Gestational age (weeks)") +
ylab("Birthweight (grams)") +
theme(legend.position = "bottom") +
# expand_limits(y = 0, x = 0) +
geom_point(alpha = .7)
print(plot1 + facet_wrap(~ sex))
```
:::::
---
#### Data notation
Let's define some notation to represent this data.
- $Y$: birthweight (measured in grams)
- $S$: chromosomal sex: "male" (XY) or "female" (XX)
- $M$: indicator variable for $S$ = "male"^[$M$ is implicitly a deterministic function of $S$]
- $M = 0$ if female (XX)
- $M = 1$ if male (XY)
- $F$: indicator variable for $S$ = "female"^[$F$ is implicitly a deterministic function of $S$]
- $F = 1$ if female (XX)
- $F = 0$ if male (XY)
- $A$: estimated gestational age at birth (measured in weeks).
::: callout-note
Female is the **reference level** for the categorical variable $S$
(chromosomal sex) and corresponding indicator variable $M$ .
The choice of a reference level is arbitrary and does not limit what
we can do with the resulting model;
it only makes it more computationally convenient to make inferences
about comparisons involving that reference group.
:::
### Parallel lines regression
We don't have enough data to model the distribution of birth weight
separately for each combination of gestational age and sex,
so let's instead consider a (relatively) simple model for how that
distribution varies with gestational age and sex:
$$p(Y=y|A=a,S=s) \siid N(\mu(a,s), \sigma^2)$$
$$
\ba
\mu(a,s)
&\eqdef \Exp{Y|A=a, S=s} \\
&= \beta_0 + \beta_A a+ \beta_M m
\ea
$$ {#eq-lm-parallel}
:::{.notes}
@tbl-lm-parallel shows the parameter estimates from R.
@fig-parallel-fit1 shows the estimated model, superimposed on the data.
:::
::: {.column width=40%}
```{r}
#| label: tbl-lm-parallel
#| tbl-cap: "Estimate of [Model @eq-lm-parallel] for `birthweight` data"
bw_lm1 = lm(
formula = weight ~ sex + age,
data = bw)
bw_lm1 |>
parameters() |>
print_md(
include_reference = TRUE,
# show_sigma = TRUE,
select = "{estimate}")
```
:::
:::{.column width=10%}
:::
:::{.column width=50%}
```{r}
#| label: fig-parallel-fit1
#| fig-cap: "Parallel-slopes model of birthweight"
bw =
bw |>
mutate(`E[Y|X=x]` = fitted(bw_lm1)) |>
arrange(sex, age)
plot2 =
plot1 %+% bw +
geom_line(aes(y = `E[Y|X=x]`))
print(plot2)
```
:::
---
#### Model assumptions and predictions
::: notes
To learn what this model is assuming, let's plug in a few values.
:::
::: {#exr-pred-fem-parallel}
According to this model, what's the mean birthweight for a female born at 36 weeks?
```{r}
#| tbl-cap: "Estimated coefficients for [model @eq-lm-parallel]"
#| label: tbl-coef-model1
coef(bw_lm1)
```
:::
---
:::{.solution}
\
```{r}
pred_female = coef(bw_lm1)["(Intercept)"] + coef(bw_lm1)["age"]*36
coef(bw_lm1)
# print(pred_female)
### built-in prediction:
# predict(bw_lm1, newdata = tibble(sex = "female", age = 36))
```
$$
\ba
E[Y|A = 0, A = 36]
&= \beta_0 + \beta_M \cdot 0+ \beta_A \cdot 36 \\
&= `r pred_female`
\ea
$$
:::
---
:::{#exr-pred-male-parallel}
What's the mean birthweight for a male born at 36 weeks?
```{r}
coef(bw_lm1)
```
:::
---
:::{.solution}
\
```{r}
pred_male =
coef(bw_lm1)["(Intercept)"] +
coef(bw_lm1)["sexmale"] +
coef(bw_lm1)["age"]*36
coef(bw_lm1)
```
$$
\ba
E[Y|M = 1, A = 36]
&= \beta_0 + \beta_M \cdot 1+ \beta_A \cdot 36 \\
&= `r pred_male`
\ea
$$
:::
---
:::{#exr-diff-sex-parallel-1}
What's the difference in mean birthweights between males born at 36 weeks and females born at 36 weeks?
:::
```{r}
coef(bw_lm1)
```
---
:::{.solution}
$$
\begin{aligned}
& E[Y|M = 1, A = 36] - E[Y|M = 0, A = 36]\\
&=
`r pred_male` - `r pred_female`\\
&=
`r pred_male - pred_female`
\end{aligned}
$$
Shortcut:
$$
\begin{aligned}
& E[Y|M = 1, A = 36] - E[Y|M = 0, A = 36]\\
&= (\beta_0 + \beta_M \cdot 1+ \beta_A \cdot 36) -
(\beta_0 + \beta_M \cdot 0+ \beta_A \cdot 36) \\
&= \beta_M \\
&= `r coef(bw_lm1)["sexmale"]`
\end{aligned}
$$
:::
:::{.notes}
Note that age doesn't show up in this difference: in other words, according to this model, the difference between females and males with the same gestational age is the same for every age.
That's an assumption of the model; it's built-in to the parametric structure, even before we plug in the estimated values of those parameters.
That's why the lines are parallel.
:::
### Interactions {.smaller}
:::{.notes}
What if we don't like that parallel lines assumption?
Then we need to allow an "interaction" between age $A$ and sex $S$:
:::
$$
E[Y|A=a, S=s] = \beta_0 + \beta_A a+ \beta_M m + \beta_{AM} (a \cdot m)
$$ {#eq-BW-lm-interact}
::: notes
Now, the slope of mean birthweight $E[Y|A,S]$ with respect to gestational age $A$ depends on the value of sex $S$.
:::
::: {.column width=40% .smaller}
```{r}
#| label: tbl-bw-model-coefs-interact
#| tbl-cap: "Birthweight model with interaction term"
bw_lm2 = lm(weight ~ sex + age + sex:age, data = bw)
bw_lm2 |>
parameters() |>
print_md(
include_reference = TRUE,
# show_sigma = TRUE,
select = "{estimate}")
```
:::
:::{.column width=5%}
:::
:::{.column width=55%}
```{r}
#| label: fig-bw-interaction
#| fig-cap: "Birthweight model with interaction term"
bw =
bw |>
mutate(
predlm2 = predict(bw_lm2)
) |>
arrange(sex, age)
plot1_interact =
plot1 %+% bw +
geom_line(aes(y = predlm2))
print(plot1_interact)
```
:::
::: {.notes}
Now we can see that the lines aren't parallel.
:::
---
Here's another way we could rewrite this model (by collecting terms involving $S$):
$$
E[Y|A, M] = \beta_0 + \beta_M M+ (\beta_A + \beta_{AM} M) A
$$
::: callout-note
If you want to understand a coefficient in a model with interactions, collect terms for the corresponding variable, and you will see what other variables are interacting with the variable you are interested in.
:::
:::{.notes}
In this case, the coefficient $S$ is interacting with $A$. So the slope of $Y$ with respect to $A$ depends on the value of $M$.
According to this model, there is no such thing as "*the* slope of birthweight with respect to age". There are two slopes, one for each sex.^[using the definite article "the" would mean there is only one slope.] We can only talk about "the slope of birthweight with respect to age among males" and "the slope of birthweight with respect to age among females".
Then: that coefficient is the difference in means per unit change in its corresponding coefficient, when the other collected variables are set to 0.
:::
---
::: notes
To learn what this model is assuming, let's plug in a few values.
:::
:::{#exr-pred-fem-interact}
According to this model, what's the mean birthweight for a female born at 36 weeks?
:::
---
::: {.solution}
\
```{r}
pred_female = coef(bw_lm2)["(Intercept)"] + coef(bw_lm2)["age"]*36
```
$$
E[Y|A = 0, X_2 = 36] =
\beta_0 + \beta_M \cdot 0+ \beta_A \cdot 36 + \beta_{AM} \cdot (0 * 36)
= `r pred_female`
$$
:::
---
:::{#exr-pred-interact-male_36}
What's the mean birthweight for a male born at 36 weeks?
:::
---
::: solution
\
```{r}
pred_male =
coef(bw_lm2)["(Intercept)"] +
coef(bw_lm2)["sexmale"] +
coef(bw_lm2)["age"]*36 +
coef(bw_lm2)["sexmale:age"] * 36
```
$$
\ba
E[Y|A = 0, X_2 = 36]
&= \beta_0 + \beta_M \cdot 1+ \beta_A \cdot 36 + \beta_{AM} \cdot 1 \cdot 36\\
&= `r pred_male`
\ea
$$
:::
---
:::{#exr-diff-gender-interact}
What's the difference in mean birthweights between males born at 36 weeks and females born at 36 weeks?
:::
---
:::{.solution}
$$
\begin{aligned}
& E[Y|M = 1, A = 36] - E[Y|M = 0, A = 36]\\
&= (\beta_0 + \beta_M \cdot 1+ \beta_A \cdot 36 + \beta_{AM} \cdot 1 \cdot 36)\\
&\ \ \ \ \ -(\beta_0 + \beta_M \cdot 0+ \beta_A \cdot 36 + \beta_{AM} \cdot 0 \cdot 36) \\
&= \beta_{S} + \beta_{AM}\cdot 36\\
&= `r pred_male - pred_female`
\end{aligned}
$$
:::
:::{.notes}
Note that age now does show up in the difference: in other words, according to this model, the difference in mean birthweights between females and males with the same gestational age can vary by gestational age.
That's how the lines in the graph ended up non-parallel.
:::
### Stratified regression {.smaller}
:::{.notes}
We could re-write the interaction model as a stratified model, with a slope and intercept for each sex:
:::
$$
\E{Y|A=a, S=s} =
\beta_M m + \beta_{AM} (a \cdot m) +
\beta_F f + \beta_{AF} (a \cdot f)
$$ {#eq-model-strat}
Compare this stratified model with our interaction model, @eq-BW-lm-interact:
$$
\E{Y|A=a, S=s} =
\beta_0 + \beta_A a + \beta_M m + \beta_{AM} (a \cdot m)
$$
::: notes
In the stratified model, the intercept term $\beta_0$ has been relabeled as $\beta_F$.
:::
::: {.column width=45%}
```{r}
#| label: tbl-bw-model-coefs-interact2
#| tbl-cap: "Birthweight model with interaction term"
bw_lm2 = lm(weight ~ sex + age + sex:age, data = bw)
bw_lm2 |>
parameters() |>
print_md(
include_reference = TRUE,
# show_sigma = TRUE,
select = "{estimate}")
```
:::
:::{.column width=10%}
:::
:::{.column width=45%}
```{r}
#| label: tbl-bw-model-coefs-strat
#| tbl-cap: "Birthweight model - stratified betas"
bw_lm_strat =
bw |>
lm(
formula = weight ~ sex + sex:age - 1,
data = _)
bw_lm_strat |>
parameters() |>
print_md(
# show_sigma = TRUE,
select = "{estimate}")
```
:::
### Curved-line regression
::: notes
If we transform some of our covariates ($X$s) and plot the resulting model on the original covariate scale, we end up with curved regression lines:
:::
```{r}
#| label: fig-penguins-log-x
#| fig-cap: "`palmerpenguins` model with `bill_length` entering on log scale"
bw_lm3 = lm(weight ~ sex:log(age) - 1, data = bw)
library(palmerpenguins)
ggpenguins <-
palmerpenguins::penguins |>
dplyr::filter(species == "Adelie") |>
ggplot(
aes(x = bill_length_mm , y = body_mass_g)) +
geom_point() +
xlab("Bill length (mm)") +
ylab("Body mass (g)")
ggpenguins2 = ggpenguins +
stat_smooth(
method = "lm",
formula = y ~ log(x),
geom = "smooth") +
xlab("Bill length (mm)") +
ylab("Body mass (g)")
ggpenguins2 |> print()
```
## Estimating Linear Models via Maximum Likelihood {#sec-est-LMs}
### Likelihood, log-likelihood, and score functions for linear regression {.smaller}
:::{.notes}
In EPI 203 and @sec-intro-MLEs, we learned how to fit outcome-only models of the form $p(X=x|\theta)$ to iid data $\vx = (x_1,…,x_n)$ using maximum likelihood estimation.
Now, we apply the same procedure to linear regression models:
:::
$$
\mathcal L(\vec y|\mat x,\beta, \sigma^2) =
\prod_{i=1}^n (2\pi\sigma^2)^{-1/2}
\exp{-\frac{1}{2\sigma^2}(y_i - \vec{x_i}'\beta)^2}
$$ {#eq-linreg-lik}
$$
\ell(\vec y|\mat x,\beta, \sigma^2)
= -\frac{n}{2}\log{\sigma^2} -
\frac{1}{2\sigma^2}\sum_{i=1}^n (y_i - \vec{x_i}' \beta)^2
$$ {#eq-linreg-loglik}
$$
\ell'_{\beta}(\vec y|\mat x,\beta, \sigma^2)
= -
\frac{1}{2\sigma^2}\deriv{\beta}
\paren{\sum_{i=1}^n (y_i - \vec{x_i}\' \beta)^2}
$$ {#eq-linreg-score}
---
::: notes
Let's switch to matrix-vector notation:
:::
$$
\sum_{i=1}^n (y_i - \vx_i\' \vb)^2
= (\vy - \mX\vb)'(\vy - \mX\vb)
$$
---
So
$$
\begin{aligned}
(\vy - \mX\vb)'(\vy - \mX\vb)
&= (\vy' - \vb'X')(\vy - \mX\vb)
\\ &= y'y - \vb'X'y - y'\mX\vb +\vb'\mX'\mX\beta
\\ &= y'y - 2y'\mX\beta +\beta'\mX'\mX\beta
\end{aligned}
$$
### Deriving the linear regression score function
::: notes
We will use some results from [vector calculus](math-prereqs.qmd#sec-vector-calculus):
:::
$$
\begin{aligned}
\deriv{\beta}\paren{\sum_{i=1}^n (y_i - x_i' \beta)^2}
&= \deriv{\beta}(\vy - X\beta)'(\vy - X\beta)
\\ &= \deriv{\beta} (y'y - 2y'X\beta +\beta'X'X\beta)
\\ &= (- 2X'y +2X'X\beta)
\\ &= - 2X'(y - X\beta)
\\ &= - 2X'(y - \Expp[y])
\\ &= - 2X' \err(y)
\end{aligned}
$${#eq-scorefun-linreg}
---
So if $\ell(\beta,\sigma^2) =0$, then
$$
\begin{aligned}
0 &= (- 2X'y +2X'X\beta)\\
2X'y &= 2X'X\beta\\
X'y &= X'X\beta\\
(X'X)^{-1}X'y &= \beta
\end{aligned}
$$
---
The second derivative matrix $\ell_{\beta, \beta'} ''(\beta, \sigma^2;\mathbf X,\vy)$ is negative definite at $\beta = (X'X)^{-1}X'y$, so $\hat \beta_{ML} = (X'X)^{-1}X'y$ is the MLE for $\beta$.
---
Similarly (not shown):
$$
\hat\sigma^2_{ML} = \frac{1}{n} (Y-X\hat\beta)'(Y-X\hat\beta)
$$
And
$$
\begin{aligned}
\mathcal I_{\beta} &= E[-\ell_{\beta, \beta'} ''(Y|X,\beta, \sigma^2)]\\
&= \frac{1}{\sigma^2}X'X
\end{aligned}
$$
---
So:
$$
Var(\hat \beta) \approx (\mathcal I_{\beta})^{-1} = \sigma^2 (X'X)^{-1}
$$
and
$$
\hat\beta \dot \sim N(\beta, \mathcal I_{\beta}^{-1})
$$
:::{.notes}
These are all results you have hopefully seen before.
:::
---
In the Gaussian linear regression case, we also have exact results:
$$
\frac{\hat\beta_j}{\hse{\hat\beta_j}} \dist t_{n-p}
$$
---
In our model 2 above, $\heinf(\beta)$ is:
```{r}
bw_lm2 |> vcov()
```
If we take the square roots of the diagonals, we get the standard errors listed in the model output:
```{r}
bw_lm2 |> vcov() |> diag() |> sqrt()
```
```{r}
#| label: tbl-mod-intx
#| tbl-cap: "Estimated model for `birthweight` data with interaction term"
bw_lm2 |> parameters() |> print_md()
```
So we can do confidence intervals, hypothesis tests, and p-values exactly as in the one-variable case we looked at previously.
### Residual Standard Deviation
::: notes
$\hs$ represents an *estimate* of the *Residual Standard Deviation* parameter, $\s$.
We can extract $\hs$ from the fitted model, using the `sigma()` function:
:::
```{r}
#| code-fold: show
sigma(bw_lm2)
```
---
#### $\s$ is NOT "Residual standard error"
::: notes
In the `summary.lm()` output, this estimate is labeled as `"Residual standard error"`:
:::
```{r}
#| code-fold: show
summary(bw_lm2)
```
---
::: notes
However, this is a misnomer:
:::
```{r, printr.help.sections = c("description", "note")}
#| code-fold: show
library(printr) # captures ? documentation
?stats::sigma
```
## Inference about Gaussian Linear Regression Models {#sec-infer-LMs}
### Motivating example: `birthweight` data
Research question: is there really an interaction between sex and age?
$H_0: \beta_{AM} = 0$
$H_A: \beta_{AM} \neq 0$
$P(|\hat\beta_{AM}| > |`r coef(bw_lm2)["sexmale:age"]`| \mid H_0)$ = ?
### Wald tests and CIs {.smaller}
R can give you Wald tests for single coefficients and corresponding CIs:
```{r "wald tests bw_lm2"}
bw_lm2 |>
parameters() |>
print_md(
include_reference = TRUE)
```
To understand what's happening, let's replicate these results by hand for the interaction term.
### P-values {.smaller}
```{r}
bw_lm2 |>
parameters(keep = "sexmale:age") |>
print_md(
include_reference = TRUE)
```
```{r}
beta_hat = coef(summary(bw_lm2))["sexmale:age", "Estimate"]
se_hat = coef(summary(bw_lm2))["sexmale:age", "Std. Error"]
dfresid = bw_lm2$df.residual
t_stat = abs(beta_hat)/se_hat
pval_t =
pt(-t_stat, df = dfresid, lower.tail = TRUE) +
pt(t_stat, df = dfresid, lower.tail = FALSE)
```
$$
\begin{aligned}
&P\paren{
| \hat \beta_{AM} | >
| `r coef(bw_lm2)["sexmale:age"]`| \middle| H_0
}
\\
&= \Pr \paren{
\abs{ \frac{\hat\beta_{AM}}{\hat{SE}(\hat\beta_{AM})} } >
\abs{ \frac{`r beta_hat`}{`r se_hat`} } \middle| H_0
}\\
&= \Pr \paren{
\abs{ T_{`r dfresid`} } > `r t_stat` | H_0
}\\
&= `r pval_t`
\end{aligned}
$$
::: notes
This matches the result in the table above.
:::
### Confidence intervals
```{r}
bw_lm2 |>
parameters(keep = "sexmale:age") |>
print_md(
include_reference = TRUE)
```
```{r}
#| label: confint-t
q_t = qt(
p = 0.975,
df = dfresid,
lower.tail = TRUE)
q_t = qt(
p = 0.025,
df = dfresid,
lower.tail = TRUE)
confint_radius_t =
se_hat * q_t
confint_t = beta_hat + c(-1,1) * confint_radius_t
print(confint_t)
```
::: notes
This also matches.
:::
### Gaussian approximations
Here are the asymptotic (Gaussian approximation) equivalents:
### P-values {.smaller}
```{r}
bw_lm2 |>
parameters(keep = "sexmale:age") |>
print_md(
include_reference = TRUE)
```
```{r}
pval_z = pnorm(abs(t_stat), lower = FALSE) * 2
print(pval_z)
```
### Confidence intervals {.smaller}
```{r}
bw_lm2 |>
parameters(keep = "sexmale:age") |>
print_md(
include_reference = TRUE)
```
```{r}
confint_radius_z = se_hat * qnorm(0.975, lower = TRUE)
confint_z =
beta_hat + c(-1,1) * confint_radius_z
print(confint_z)
```
### Likelihood ratio statistics
```{r}
logLik(bw_lm2)
logLik(bw_lm1)
lLR = (logLik(bw_lm2) - logLik(bw_lm1)) |> as.numeric()
delta_df = (bw_lm1$df.residual - df.residual(bw_lm2))
x_max = 1
```
---
```{r}
#| label: fig-chisq-plot
#| fig-cap: "Chi-square distribution"
d_lLR = function(x, df = delta_df) dchisq(x, df = df)
chisq_plot =
ggplot() +
geom_function(fun = d_lLR) +
stat_function( fun = d_lLR, xlim = c(lLR, x_max), geom = "area", fill = "gray") +
geom_segment(aes(x = lLR, xend = lLR, y = 0, yend = d_lLR(lLR)), col = "red") +
xlim(0.0001,x_max) +
ylim(0,4) +
ylab("p(X=x)") +
xlab("log(likelihood ratio) statistic [x]") +
theme_classic()
chisq_plot |> print()
```
---
Now we can get the p-value:
```{r}
#| label: LRT-pval
pchisq(
q = 2*lLR,
df = delta_df,
lower = FALSE) |>
print()
```
---
In practice you don't have to do this by hand; there are functions to do it for you: