-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.qmd
2508 lines (1962 loc) · 75.2 KB
/
index.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
```{r}
#| label: setup
#| include: false
source(here::here("R/quarto-setup.R"))
```
<!-- badges: start -->
[![Project Status: Inactive – The project has reached a stable, usable state but is no longer being actively developed; support/maintenance will be provided as time allows.](https://www.repostatus.org/badges/latest/inactive.svg)](https://www.repostatus.org/#inactive)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://choosealicense.com/licenses/mit/)
<!-- badges: end -->
## Overview
This document demonstrates the application of [general linear models](https://en.wikipedia.org/wiki/General_linear_model), with a focus on multiple regression. It utilizes the [`penguins`](https://allisonhorst.github.io/palmerpenguins/reference/penguins.html) dataset from the [`palmerpenguins`](https://github.com/allisonhorst/palmerpenguins/) R package, which contains measurements of penguin species from the [Palmer Archipelago](https://en.wikipedia.org/wiki/Palmer_Archipelago). The dataset was originally introduced by @gorman2014.
::: {#fig-penguins-1}
![](images/palmer_penguins.png){fig-align="center" width="75%"}
Artwork by [Allison Horst](https://allisonhorst.com/).
:::
## Question
Every scientific investigation begins with a question. In this case, we will address the following:
**Can bill length and bill depth alone effectively predict flipper length in [Adélie penguins](https://en.wikipedia.org/wiki/Ad%C3%A9lie_penguin)?**
Imagine a debate between two marine biologists: one claims that bill length and depth could be used to predict flipper length, while the other disagrees.
To investigate this question, we will utilize a dataset from the [`palmerpenguins`](https://github.com/allisonhorst/palmerpenguins/) R package. The relevant variables are `bill_length_mm`,`bill_depth_mm` and `flipper_length_mm` for Adélie penguins. These variables are [defined](https://allisonhorst.github.io/palmerpenguins/reference/penguins.html) as follows:
- `bill_length_mm`: Numerical value representing the bill's length in millimeters.
- `bill_depth_mm`: Numerical value representing the bill's depth in millimeters.
- `flipper_length_mm`: Integer value representing the flipper's length in millimeters.
::: {#fig-penguins-2}
![](images/culmen_depth.png){fig-align="center"width="75%"}
Artwork by [Allison Horst](https://allisonhorst.com/).
:::
## Hypothesis
To approach our question, we will apply Popper’s hypothetico-deductive method, also known as the *method of conjecture and refutation* [@popper1979, p. 164]. The basic structure of this approach can be summarized as follows:
```{mermaid}
%%| label: fig-mermaid
%%| fig-cap: Simplified schema of Popper’s hypothetico-deductive method.
%%| fig-align: center
flowchart LR
A(P1) --> B(TT)
B --> C(EE)
C --> D(P2)
```
"Here $\text{P}_1$, is the **problem** from which we start, $\text{TT}$ (the ‘tentative theory’) is the imaginative conjectural solution which we first reach, for example our first **tentative interpretation**. $\text{EE}$ (‘**error- elimination**’) consists of a severe critical examination of our conjecture, our tentative interpretation: it consists, for example, of the critical use of documentary evidence and, if we have at this early stage more than one conjecture at our disposal, it will also consist of a critical discussion and comparative evaluation of the competing conjectures. $\text{P}_2$ is the problem situation as it emerges from our first critical attempt to solve our problems.
It leads up to our second attempt (**and so on**)." [@popper1979, p. 164]
As our tentative theory or main hypothesis, I propose the following:
**Bill length and bill depth can effectively predict flipper length in Adélie penguins**.
As a procedure method, we will employ a method **inpired** by the Neyman-Pearson approach to data testing [@neyman1928; @neyman1928a; @perezgonzalez2015], evaluating the following hypotheses:
$$
\begin{cases}
\text{H}_{0}: \text{Bill length and bill depth cannot effectively predict flipper length in Adélie penguins} \\
\text{H}_{a}: \text{Bill length and bill depth can effectively predict flipper length in Adélie penguins}
\end{cases}
$$
::: {.callout-warning}
Technically, our procedural method is not a strictly Neyman-Pearson acceptance test; we might refer to it as an improved [NHST](https://en.wikipedia.org/wiki/Statistical_hypothesis_test) (Null Hypothesis Significance Testing) approach, based on the original Neyman-Pearson ideas.
:::
## Methods
To test our hypothesis, we will use a general linear model with multiple regression analysis, evaluating the relationship between multiple predictors and a response variable. Here, the response variable is `flipper_length_mm`, while the predictors are `bill_length_mm` and `bill_depth_mm`.
To define what we mean by *effectively predict*" we will establish the following decision criteria:
- Predictors should exhibit a statistically significant association with the response variable.
- The model should satisfy all validity assumptions.
- The variance explained by the predictors ($\text{R}^{2}_{\text{adj}}$) must exceed 0.5, suggesting a strong association with the response variable ($\text{Cohen's } f^2 = \cfrac{0.5}{1 - 0.5} = 1$.)
This 0.5 threshold is not arbitrary; it represents the average level of variance explained in response variables during observational field studies in ecology, especially when there is limited control over factors influencing variance [@peek2003].
Finally, our hypothesis test can be systematized as follows:
$$
\begin{cases}
\text{H}_{0}: \text{R}^{2}_{\text{adj}} \leq 0.5 \\
\text{H}_{a}: \text{R}^{2}_{\text{adj}} > 0.5
\end{cases}
$$
In addition to an adjusted R-squared greater than 0.5, we will require predictors to show statistically significant associations and for the model to meet all assumptions.
We will set the significance level ($\alpha$) at 0.05, allowing a 5% chance of a [Type I error](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors). A power analysis will be performed to determine the necessary sample size for detecting a significant effect, targeting a power ($1 - \beta$) of 0.8.
Assumption checks will include:
- Assessing the normality of residuals through visual inspections, such as [Q-Q plots](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot), and statistical tests like the [Shapiro-Wilk test](https://en.wikipedia.org/wiki/Shapiro%E2%80%93Wilk_test).
- Evaluating homoscedasticity using tests like the [Breusch-Pagan test](https://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test) to ensure constant variance of residuals across predictor levels.
We will assess multicollinearity by calculating variance inflation factors ([VIF](https://en.wikipedia.org/wiki/Variance_inflation_factor)), with a VIF above 10 indicating potential issues. Influential points will be examined using [Cook's distance](https://en.wikipedia.org/wiki/Cook%27s_distance) and leverage values to identify any points that may disproportionately affect model outcomes.
::: {.callout-note}
It's important to emphasize that we are assessing predictive power, not establishing causality. Predictive models alone should never be used to infer causal relationships [@arif2022].
:::
## An overview of general linear models
Before proceeding, let's briefly overview general linear models, with a focus on multiple regression analysis.
"[...] A problem of this type is called a problem of multiple linear regression because we are considering the regression of $Y$ on $k$ variables $X_{1}, \dots, X_{k}$, rather than on just a single variable $X$, and we are assuming also that this regression is a linear function of the parameters $\beta_{0}, \dots, \beta_{k}$. In a problem of multiple linear regressions, we obtain $n$ vectors of observations ($x_{i1}. \dots, x_{ik}, Y_{i}$), for $i = 1, \dots, n$. Here $x_{ij}$ is the observed value of the variable $X_{j}$ for the $i$th observation. The $E(Y)$ is given by the relation
$$
E(Y_{i}) = \beta_{0} + \beta_{1} x_{i1} + \dots + \beta_{k} x_{ik}
$$
[@degroot2012, p. 738]
### Definitions
Residuals/Fitted values
: \hspace{20cm} For $i = 1, \dots, n$, the observed values of $\hat{y} = \hat{\beta}_{0} + \hat{\beta}_{1} x_{i}$ are called _fitted values_. For $i = 1, \dots, n$, the observed values of $e_{i} = y_{i} - \hat{y}_{i}$ are called _residuals_ [@degroot2012, p. 717].
"[...] regression problems in which the observations $Y_{i}, \dots, Y_{n}$ [...] we shall assume that each observation $Y_{i}$ has a normal distribution, that the observations $Y_{1}, \dots, Y_{n}$ are independent, and that the observations $Y_{1}, \dots, Y_{n}$ have the same variance $\sigma^{2}$. Instead of a single predictor being associated with each $Y_{i}$, we assume that a $p$-dimensional vector $z_{i} = (z_{i0}, \dots, z_{ip - 1})$ is associated with each $Y_{i}$" [@degroot2012, p. 736].
General linear model
: The statistical model in which the observations $Y_{1}, \dots, Y_{n}$ satisfy the following assumptions [@degroot2012, p. 738].
### Assumptions
Assumption 1
: \hspace{20cm} __Predictor is known__. Either the vectors $z_{1}, \dots , z_{n}$ are known ahead of time, or they are the observed values of random vectors $Z_{1}, \dots , Z_{n}$ on whose values we condition before computing the joint distribution of ($Y_{1}, \dots , Y_{n}$) [@degroot2012, p. 736].
Assumption 2
: \hspace{20cm} __Normality__. For $i = 1, \dots, n$, the conditional distribution of $Y_{i}$ given the vectors $z_{1}, \dots , z_{n}$ is a normal distribution [@degroot2012, p. 737].
(Normality of the error term distribution [@hair2019, p. 287])
Assumption 3
: \hspace{20cm} __Linear mean__. There is a vector of parameters $\beta = (\beta_{0}, \dots, \beta_{p - 1})$ such that the conditional mean of $Y_{i}$ given the values $z_{1}, \dots , z_{n}$ has the form
$$
z_{i0} \beta_{0} + z_{i1} \beta_{1} + \cdots + z_{ip - 1} \beta_{p - 1}
$$
for $i = 1, \dots, n$ [@degroot2012, p. 737].
(Linearity of the phenomenon measured [@hair2019, p. 287])
::: {.callout-warning}
It is important to clarify that the linear assumption pertains to **linearity in the parameters** or equivalently, linearity in the coefficients. This means that each predictor is multiplied by its corresponding regression coefficient. However, this does not imply that the relationship between the predictors and the response variable is linear. In fact, a linear model can still effectively capture non-linear relationships between predictors and the response variable by utilizing transformations of the predictors [@cohen2002].
:::
Assumption 4
: \hspace{20cm} __Common variance__ (homoscedasticity). There is as parameter $\sigma^{2}$ such the conditional variance of $Y_{i}$ given the values $z_{1}, \dots , z_{n}$ is $\sigma^{2}$ for $i = 1, \dots, n$.
(Constant variance of the error terms [@hair2019, p. 287])
Assumption 5
: \hspace{20cm} __Independence__. The random variables $Y_{1}, \dots , Y_{n}$ are independent given the observed $z_{1}, \dots , z_{n}$ [@degroot2012, p. 737].
(Independence of the error terms [@hair2019, p. 287])
## Setting up the environment
```{r}
#| eval: false
#| code-fold: true
library(broom)
library(car)
library(checkmate)
library(cowplot)
library(dplyr)
library(effectsize)
library(fBasics)
library(forecast)
library(ggeffects)
library(GGally)
library(ggplot2)
library(ggpmisc)
library(ggplotify)
library(qqplotr)
library(ggPredict)
library(glue)
library(insight)
library(janitor)
library(latex2exp)
library(magrittr)
library(moments)
library(nortest)
library(olsrr)
library(palmerpenguins)
library(parameters)
library(parsnip)
library(performance)
library(predict3d)
library(psychometric)
library(pwrss)
library(recipes)
library(report)
library(rgl)
library(rutils)
library(sandwich)
library(stats)
library(stringr)
library(tidyr)
library(tseries)
library(viridis)
library(workflows)
```
```{r}
#| include: false
library(magrittr)
```
```{r}
#| code-fold: true
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
```
```{r}
#| code-fold: true
lm_fun <- function(model, fix_all_but = NULL, data = NULL) {
checkmate::assert_class(model, "lm")
checkmate::assert_number(
fix_all_but,
lower = 1,
upper = length(stats::coef(model)) - 1,
null.ok = TRUE
)
coef <- broom::tidy(fit)
vars <- letters[seq_len((nrow(coef) - 1))]
fixed_vars <- vars
if (!is.null(fix_all_but)) {
checkmate::assert_data_frame(data)
checkmate::assert_subset(coef$term[-1], names(data))
for (i in seq_along(fixed_vars)[-fix_all_but]) {
fixed_vars[i] <- mean(data[[coef$term[i + 1]]], na.rm = TRUE)
}
vars <- vars[fix_all_but]
}
fun_exp <- str2expression(
glue::glue(
"function({paste0(vars, collapse = ', ')}) {{", "\n",
" {paste0('checkmate::assert_numeric(', vars, ')', collapse = '\n')}",
"\n\n",
" {coef$estimate[1]} +",
"{paste0(coef$estimate[-1], ' * ', fixed_vars, collapse = ' + ')}",
"\n",
"}}"
)
)
out <- eval(fun_exp)
out
}
```
```{r}
#| code-fold: true
lm_str_fun <- function(
model,
digits = 3,
latex2exp = TRUE,
fix_all_but = NULL, # Ignore the intercept coefficient.
fix_fun = "Mean",
coef_names = NULL # Ignore the intercept coefficient.
) {
checkmate::assert_class(model, "lm")
checkmate::assert_number(digits)
checkmate::assert_flag(latex2exp)
checkmate::assert_number(
fix_all_but,
lower = 1,
upper = length(stats::coef(model)) - 1,
null.ok = TRUE
)
checkmate::assert_string(fix_fun)
checkmate::assert_character(
coef_names,
any.missing = FALSE,
len = length(names(stats::coef(model))) - 1,
null.ok = TRUE
)
if (is.null(coef_names)) coef_names <- names(stats::coef(model))[-1]
coef <- list()
for (i in seq_along(coef_names)) {
coef[[coef_names[i]]] <-
stats::coef(model) |>
magrittr::extract(i + 1) |>
rutils:::clear_names() |>
round(digits)
}
coef_names <-
coef_names |>
stringr::str_replace_all("\\_|\\.", " ") |>
stringr::str_to_title() |>
stringr::str_replace(" ", "")
if (!is.null(fix_all_but)) {
for (i in seq_along(coef_names)[-fix_all_but]) {
coef_names[i] <- paste0(fix_fun, "(", coef_names[i], ")")
}
}
out <- paste0(
"$", "y =", " ",
round(stats::coef(model)[1], digits), " + ",
paste0(coef, " \\times ", coef_names, collapse = " + "),
"$"
)
out <- out |> stringr::str_replace("\\+ \\-", "\\- ")
if (isTRUE(latex2exp)) {
out |>latex2exp::TeX()
} else {
out
}
}
```
```{r}
#| code-fold: true
test_outlier <- function(
x,
method = "iqr",
iqr_mult = 1.5,
sd_mult = 3
) {
checkmate::assert_numeric(x)
checkmate::assert_choice(method, c("iqr", "sd"))
checkmate::assert_number(iqr_mult)
checkmate::assert_number(sd_mult)
if (method == "iqr") {
iqr <- stats::IQR(x, na.rm = TRUE)
min <- stats::quantile(x, 0.25, na.rm = TRUE) - (iqr_mult * iqr)
max <- stats::quantile(x, 0.75, na.rm = TRUE) + (iqr_mult * iqr)
} else if (method == "sd") {
min <- mean(x, na.rm = TRUE) - (sd_mult * stats::sd(x, na.rm = TRUE))
max <- mean(x, na.rm = TRUE) + (sd_mult * stats::sd(x, na.rm = TRUE))
}
dplyr::if_else(x >= min & x <= max, FALSE, TRUE, missing = FALSE)
}
```
```{r}
#| code-fold: true
remove_outliers <- function(
x,
method = "iqr",
iqr_mult = 1.5,
sd_mult = 3
) {
checkmate::assert_numeric(x)
checkmate::assert_choice(method, c("iqr", "sd"))
checkmate::assert_number(iqr_mult, lower = 1)
checkmate::assert_number(sd_mult, lower = 0)
x |>
test_outlier(
method = method,
iqr_mult = iqr_mult,
sd_mult = sd_mult
) %>%
`!`() %>%
magrittr::extract(x, .)
}
```
```{r}
#| code-fold: true
list_as_tibble <- function(list) {
checkmate::assert_list(list)
list |>
dplyr::as_tibble() |>
dplyr::mutate(
dplyr::across(
.cols = dplyr::everything(),
.fns = as.character
)
) |>
tidyr::pivot_longer(cols = dplyr::everything())
}
```
```{r}
#| code-fold: true
stats_sum <- function(
x,
name = NULL,
na_rm = TRUE,
remove_outliers = FALSE,
iqr_mult = 1.5,
as_list = FALSE
) {
checkmate::assert_numeric(x)
checkmate::assert_string(name, null.ok = TRUE)
checkmate::assert_flag(na_rm)
checkmate::assert_flag(remove_outliers)
checkmate::assert_number(iqr_mult, lower = 1)
checkmate::assert_flag(as_list)
if (isTRUE(remove_outliers)) {
x <- x |> remove_outliers(method = "iqr", iqr_mult = iqr_mult)
}
out <- list(
n = length(x),
n_rm_na = length(x[!is.na(x)]),
n_na = length(x[is.na(x)]),
mean = mean(x, na.rm = na_rm),
var = stats::var(x, na.rm = na_rm),
sd = stats::sd(x, na.rm = na_rm),
min = rutils:::clear_names(stats::quantile(x, 0, na.rm = na_rm)),
q_1 = rutils:::clear_names(stats::quantile(x, 0.25, na.rm = na_rm)),
median = rutils:::clear_names(stats::quantile(x, 0.5, na.rm = na_rm)),
q_3 = rutils:::clear_names(stats::quantile(x, 0.75, na.rm = na_rm)),
max = rutils:::clear_names(stats::quantile(x, 1, na.rm = na_rm)),
iqr = IQR(x, na.rm = na_rm),
skewness = moments::skewness(x, na.rm = na_rm),
kurtosis = moments::kurtosis(x, na.rm = na_rm)
)
if (!is.null(name)) out <- append(out, list(name = name), after = 0)
if (isTRUE(as_list)) {
out
} else {
out |> list_as_tibble()
}
}
```
```{r}
#| code-fold: true
plot_qq <- function(
x,
text_size = NULL,
na_rm = TRUE,
print = TRUE
) {
checkmate::assert_numeric(x)
checkmate::assert_number(text_size, null.ok = TRUE)
checkmate::assert_flag(na_rm)
checkmate::assert_flag(print)
if (isTRUE(na_rm)) x <- x |> rutils:::drop_na()
plot <-
dplyr::tibble(y = x) |>
ggplot2::ggplot(ggplot2::aes(sample = y)) +
ggplot2::stat_qq() +
ggplot2::stat_qq_line(color = "red", linewidth = 1) +
ggplot2::labs(
x = "Theoretical quantiles (Std. normal)",
y = "Sample quantiles"
) +
ggplot2::theme(text = ggplot2::element_text(size = text_size))
if (isTRUE(print)) print(plot)
invisible(plot)
}
```
```{r}
#| code-fold: true
plot_hist <- function(
x,
name = "x",
bins = 30,
stat = "density",
text_size = NULL,
density_line = TRUE,
na_rm = TRUE,
print = TRUE
) {
checkmate::assert_numeric(x)
checkmate::assert_string(name)
checkmate::assert_number(bins, lower = 1)
checkmate::assert_choice(stat, c("count", "density"))
checkmate::assert_number(text_size, null.ok = TRUE)
checkmate::assert_flag(density_line)
checkmate::assert_flag(na_rm)
checkmate::assert_flag(print)
if (isTRUE(na_rm)) x <- x |> rutils:::drop_na()
y_lab <- ifelse(stat == "count", "Frequency", "Density")
plot <-
dplyr::tibble(y = x) |>
ggplot2::ggplot(ggplot2::aes(x = y)) +
ggplot2::geom_histogram(
ggplot2::aes(y = ggplot2::after_stat(!!as.symbol(stat))),
bins = 30,
color = "white"
) +
ggplot2::labs(x = name, y = y_lab) +
ggplot2::theme(text = ggplot2::element_text(size = text_size))
if (stat == "density" && isTRUE(density_line)) {
plot <- plot + ggplot2::geom_density(color = "red", linewidth = 1)
}
if (isTRUE(print)) print(plot)
invisible(plot)
}
```
```{r}
#| code-fold: true
plot_ggally <- function(
data,
cols = names(data),
mapping = NULL,
axis_labels = "none",
na_rm = TRUE,
text_size = NULL
) {
checkmate::assert_tibble(data)
checkmate::assert_character(cols)
checkmate::assert_subset(cols, names(data))
checkmate::assert_class(mapping, "uneval", null.ok = TRUE)
checkmate::assert_choice(axis_labels, c("show", "internal", "none"))
checkmate::assert_flag(na_rm)
checkmate::assert_number(text_size, null.ok = TRUE)
out <-
data|>
dplyr::select(dplyr::all_of(cols))|>
dplyr::mutate(
dplyr::across(
.cols = dplyr::where(hms::is_hms),
.fns = ~ midday_trigger(.x)
),
dplyr::across(
.cols = dplyr::where(
~ !is.character(.x) && !is.factor(.x) && !is.numeric(.x)
),
.fns = ~ as.numeric(.x)
)
)
if (isTRUE(na_rm)) out <- out|> tidyr::drop_na(dplyr::all_of(cols))
if (is.null(mapping)) {
plot <-
out|>
GGally::ggpairs(
lower = list(continuous = "smooth"),
axisLabels = axis_labels
)
} else {
plot <-
out|>
GGally::ggpairs(
mapping = mapping,
axisLabels = axis_labels
) +
viridis::scale_color_viridis(
begin = 0.25,
end = 0.75,
discrete = TRUE,
option = "viridis"
) +
viridis::scale_fill_viridis(
begin = 0.25,
end = 0.75,
discrete = TRUE,
option = "viridis"
)
}
plot <-
plot +
ggplot2::theme(text = ggplot2::element_text(size = text_size))
print(plot)
invisible(plot)
}
```
```{r}
#| code-fold: true
test_normality <- function(x,
name = "x",
remove_outliers = FALSE,
iqr_mult = 1.5,
log_transform = FALSE,
density_line = TRUE,
text_size = NULL,
print = TRUE) {
checkmate::assert_numeric(x)
checkmate::assert_string(name)
checkmate::assert_flag(remove_outliers)
checkmate::assert_number(iqr_mult, lower = 1)
checkmate::assert_flag(log_transform)
checkmate::assert_flag(density_line)
checkmate::assert_number(text_size, null.ok = TRUE)
checkmate::assert_flag(print)
n <- x |> length()
n_rm_na <- x |> rutils:::drop_na() |> length()
if (isTRUE(remove_outliers)) {
x <- x |> remove_outliers(method = "iqr", iqr_mult = iqr_mult)
}
if (isTRUE(log_transform)) {
x <-
x |>
log() |>
drop_inf()
}
if (n_rm_na >= 7) {
ad <- x |> nortest::ad.test()
cvm <-
x |>
nortest::cvm.test() |>
rutils::shush()
} else {
ad <- NULL
cmv <- NULL
}
bonett <- x |> moments::bonett.test()
# See also `Rita::DPTest()` (just for Omnibus (K) tests).
dagostino <-
x |>
fBasics::dagoTest() |>
rutils::shush()
jarque_bera <-
rutils:::drop_na(x) |>
tseries::jarque.bera.test()
if (n_rm_na >= 4) {
lillie_ks <- x |> nortest::lillie.test()
} else {
lillie_ks <- NULL
}
pearson <- x |> nortest::pearson.test()
if (n_rm_na >= 5 && n_rm_na <= 5000) {
sf <- x |> nortest::sf.test()
} else {
sf <- NULL
}
if (n_rm_na >= 3 && n_rm_na <= 3000) {
shapiro <- x |> stats::shapiro.test()
} else {
shapiro <- NULL
}
qq_plot <- x |> plot_qq(text_size = text_size, print = FALSE)
hist_plot <-
x |>
plot_hist(
name = name,
text_size = text_size,
density_line = density_line,
print = FALSE
)
grid_plot <- cowplot::plot_grid(hist_plot, qq_plot, ncol = 2, nrow = 1)
out <- list(
stats = stats_sum(
x,
name = name,
na_rm = TRUE,
remove_outliers = FALSE,
as_list = TRUE
),
params = list(
name = name,
remove_outliers = remove_outliers,
log_transform = log_transform,
density_line = density_line
),
ad = ad,
bonett = bonett,
cvm = cvm,
dagostino = dagostino,
jarque_bera = jarque_bera,
lillie_ks = lillie_ks,
pearson = pearson,
sf = sf,
shapiro = shapiro,
hist_plot = hist_plot,
qq_plot = qq_plot,
grid_plot = grid_plot
)
if (isTRUE(print)) print(grid_plot)
invisible(out)
}
```
```{r}
#| code-fold: true
normality_sum <- function(
x,
round = FALSE,
digits = 5,
only_p_value = FALSE,
...
) {
checkmate::assert_numeric(x)
checkmate::assert_flag(round)
checkmate::assert_number(digits)
checkmate::assert_flag(only_p_value)
stats <- test_normality(x, print = FALSE, ...)
out <- dplyr::tibble(
test = c(
"Anderson-Darling",
"Bonett-Seier",
"Cramér-von Mises",
"D'Agostino Omnibus Test",
"D'Agostino Skewness Test",
"D'Agostino Kurtosis Test",
"Jarque–Bera",
"Lilliefors (K-S)",
"Pearson chi-square",
"Shapiro-Francia",
"Shapiro-Wilk"
),
statistic_1 = c(
stats$ad$statistic,
stats$bonett$statistic[1],
stats$cvm$statistic,
attr(stats$dagostino, "test")$statistic[1],
attr(stats$dagostino, "test")$statistic[2],
attr(stats$dagostino, "test")$statistic[3],
stats$jarque_bera$statistic,
stats$lillie_ks$statistic,
stats$pearson$statistic,
ifelse(is.null(stats$shapiro), NA, stats$shapiro$statistic),
ifelse(is.null(stats$sf), NA, stats$sf$statistic)
),
statistic_2 = c(
as.numeric(NA),
stats$bonett$statistic[2],
as.numeric(NA),
as.numeric(NA),
as.numeric(NA),
as.numeric(NA),
stats$jarque_bera$parameter,
as.numeric(NA),
as.numeric(NA),
as.numeric(NA),
as.numeric(NA)
),
p_value = c(
stats$ad$p.value,
stats$bonett$p.value,
stats$cvm$p.value,
attr(stats$dagostino, "test")$p.value[1],
attr(stats$dagostino, "test")$p.value[2],
attr(stats$dagostino, "test")$p.value[3],
stats$jarque_bera$p.value,
stats$lillie_ks$p.value,
stats$pearson$p.value,
ifelse(is.null(stats$shapiro), NA, stats$shapiro$p.value),
ifelse(is.null(stats$sf), NA, stats$sf$p.value)
)
)
if (isTRUE(only_p_value)) out <- out |> dplyr::select(test, p_value)
if (isTRUE(round)) {
out |>
dplyr::mutate(
dplyr::across(
.cols = dplyr::where(is.numeric),
.fns = ~ round(.x, digits)
))
} else {
out
}
}
```
## Preparing the data
**Assumption 1** is satisfied, as the predictors are known.
```{r}
#| code-fold: true
data <-
palmerpenguins::penguins |>
dplyr::filter(species == "Adelie") |>
dplyr::select(bill_length_mm, bill_depth_mm, flipper_length_mm) |>
tidyr::drop_na()
```
::: {#tbl-data-prep-1}
```{r}
#| code-fold: true
data
```
Data frame with morphological measurements of penguin species from the [Palmer Archipelago](https://en.wikipedia.org/wiki/Palmer_Archipelago).
:::
```{r}
report::report(data)
```
## Performing a power analysis
First we will perform a *a posteriori* power analysis to determine the sample size needed to achieve a power ($1 - \beta$) of 0.8, given an $R^2$ of 0.5, a significance level ($\alpha$) of 0.05, and 2 predictors. It's a *a posterior* analysis because we already have the data in hand. It's a good practice to perform a power analysis before running the model to ensure that the sample size is adequate.
The results show that we need at least 14 observations for each variable to achieve the desired power. We have 151 observations, which is more than enough.
```{r}
#| code-fold: true
pre_pwr <- pwrss::pwrss.f.reg(
r2 = 0.5,
k = 2,
power = 0.80,
alpha = 0.05
)
```
```{r}
#| code-fold: true
pwrss::power.f.test(
ncp = pre_pwr$ncp,
df1 = pre_pwr$df1,
df2 = pre_pwr$df2,
alpha = pre_pwr$parms$alpha,
plot = TRUE
)
```
Is the data size greater or equal to the required size?
```{r}
data |>
tidyr::drop_na() |>
nrow() |>
magrittr::is_weakly_greater_than(pre_pwr$n)
```
## Checking distributions
The data show fairly normal distributions. It seems that the `bill_length_mm` and `bill_depth_mm` variables appear slightly skewed, while the `flipper_length_mm` variable is more symmetric.
:::: {.panel-tabset}
### Bill length (mm)
::: {#tbl-var-dist-stats-sum-bill_length_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(bill_length_mm) |>
stats_sum(name = "Bill length (mm)")
```
Statistics for the `bill_length_mm` variable.
:::
::: {#fig-var-dist-hist-bill_length_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(bill_length_mm) |>
test_normality(name = "Bill length (mm)")
```
Histogram of the `bill_length_mm` variable with a kernel density estimate, along with a quantile-quantile (Q-Q) plot between the variable and the theoretical quantiles of the normal distribution.
:::
### Bill depth (mm)
::: {#tbl-var-dist-stats-sum-bill_depth_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(bill_depth_mm) |>
stats_sum(name = "Bill depth (mm)")
```
Summary statistics for the `bill_depth_mm` variable.
:::
::: {#fig-var-dist-hist-bill_depth_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(bill_depth_mm) |>
test_normality(name = "Bill depth (mm)")
```
Histogram of the `bill_depth_mm` variable with a kernel density estimate, along with a quantile-quantile (Q-Q) plot between the variable and the theoretical quantiles of the normal distribution.
:::
### Flipper length (mm)
::: {#tbl-var-dist-stats-sum-flipper_length_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(flipper_length_mm) |>
stats_sum(name = "Flipper length (mm)")
```
Summary statistics for the `flipper_length_mm` variable.
:::
::: {#fig-var-dist-hist-flipper_length_mm}
```{r}
#| code-fold: true
data |>
dplyr::pull(flipper_length_mm) |>
test_normality(name = "Flipper length (mm)")
```
Histogram of the `flipper_length_mm` variable with a kernel density estimate, along with a quantile-quantile (Q-Q) plot between the variable and the theoretical quantiles of the normal distribution.
:::
::::
## Checking correlations
Both `bill_length_mm` and `bill_depth_mm` are positively correlated with `flipper_length_mm` in a significant manner. No non-linear relationships are observed.
::: {#fig-correlations-correlation-matrix}
```{r}
#| code-fold: true
data |>
plot_ggally() |>
rutils::shush()