-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path02-time-vaying-coef-models.Rmd
494 lines (405 loc) · 12.5 KB
/
02-time-vaying-coef-models.Rmd
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
---
title: "Time-varying coefficients model using GAMs"
output:
html_document:
toc: yes
word_document:
toc: yes
editor_options:
chunk_output_type: inline
---
```{r setup, echo=FALSE}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
```
We are going to use *generalized additive models* (GAMs) to estimate time-varying coefficients for climate variables in order to quantify their effects on malaria incidence by specie thought the time period of the study.
Lets load the packages we are going to use for data reading, wrangling and analysis.
```{r message=FALSE, warning=FALSE}
# Utilities
library(htmltools)
library(tictoc)
library(fs)
# Data reading
library(readr)
library(skimr)
# Data manipulation
library(tibble)
library(lubridate)
library(dplyr)
library(scales)
library(DT)
library(stringr)
library(tidyr)
# Plots
library(ggplot2)
library(ggsci)
library(GGally)
library(DHARMa)
library(grid)
library(gridExtra)
library(graphics)
# GAM
library(mgcv)
library(gratia)
```
Setting up the theme for our plots.
```{r ggplot-setup}
ggplot2::theme_set(theme_bw())
ggplot2::theme_update(panel.grid = element_blank())
```
# Data reading
The cleaned up data can be found on the `data/processed/` directory on this repository. We are going to define the file path using the function `path()` of the `fs` packages.
```{r}
data_path <- path("data", "processed")
file_name <- "pro_malaria-monthly-cases-district-loreto.csv"
file_path <- path(data_path, file_name)
file_path
```
Create an object with the column names.
```{r message=FALSE, warning=FALSE}
col_names <- c(
"district", "year", "month", "falciparum", "vivax", "aet", "prcp", "q",
"soilm", "tmax", "tmin", "pop2015", "province", "region", "dttm", "time"
)
```
Create an object with the column types. We exclude `soilm` and `region` from the analysis.
```{r}
col_types <-
cols_only(
district = readr::col_factor(), year = readr::col_factor(),
month = readr::col_factor(),
falciparum = col_integer(), vivax = col_integer(), aet = col_double(),
prcp = col_double(), q = col_double(), tmax = col_double(),
tmin = col_double(), pop2015 = col_integer(), province = readr::col_factor(),
dttm = col_datetime(), time = col_integer()
)
```
Reading data file into a data frame.
```{r message=FALSE, warning=FALSE}
monthly_cases <-
read_csv(
file = file_path, col_names = col_names, col_types = col_types, skip = 1,
locale = readr::locale(encoding = "UTF-8")
)
```
Display the data.
```{r}
monthly_cases
```
# Data wrangling
The following wrangling pipe consists on these steps:
- Re-scale the numeric predictors (`aet`, `prcp`, `q`, `tmax` and `tmin`) from 0 to 1.
- Create a column with the population values on the natural logarithmic scale.
- For each district, create columns for the 1, 3, 6 and 12 months-lagged values of the predictors.
- Remove `NA`s from the lagged values.
```{r}
monthly_cases %>%
mutate(
across(c(aet, prcp, q, tmax, tmin), scales::rescale, to = c(0, 1)),
pop2015_ln = log(pop2015)
) %>%
group_by(district) %>%
arrange(dttm) %>%
mutate(
across(
aet:tmin,
list(
lag1 = ~ lag(.x, n = 1L), lag3 = ~ lag(.x, n = 3L),
lag6 = ~ lag(.x, n = 6L), lag12 = ~ lag(.x, n = 12L)
),
.names = "{.col}_{.fn}"
)
) %>%
na.omit() %>%
ungroup() ->
monthly_cases_analysis
```
Display the final data for analysis.
```{r}
monthly_cases_analysis
```
# Time-varying coefficients model building
## P. vivax
We start with the GAM with a time-varying effects configuration for P. vivax cases. The basis dimension `k` for the `s(district)` (random effect) term was set to 49 because there are 49 districts in the data. The remaining basis dimensions were selected by checking the test for adequacy of basis dimensions produced by the function `gam.check` iteratively until the simulated p-values were big enough to have a strong likelihood that they were adequate.
```{r message=FALSE}
tic("GAM fitting")
vivax_tvcm <- bam(
vivax ~ offset(pop2015_ln) + s(district, bs = "re", k = 49) +
s(time, by = aet, bs = "tp", k = 50) +
s(time, by = prcp, bs = "tp", k = 30) +
s(time, by = tmin, bs = "tp", k = 100),
family = nb(), data = monthly_cases_analysis, method = "fREML", discrete = TRUE
)
toc()
cat("\nConverged?", vivax_tvcm$converged, "\n")
summary(vivax_tvcm)
```
Now we check the model using the default function in the `mgcv` package for model diagnosis.
```{r include=TRUE}
par(mfrow = c(2, 2))
gam.check(vivax_tvcm)
```
We can use the `gratia` package to produce tidier outputs for GAM models using `mgcv`. Here, we use the `appraise` function to show diagnostics plots.
```{r fig.width=12, fig.height=8}
appraise(vivax_tvcm, point_col = "steelblue", point_alpha = 0.4)
```
We plot the fitted smooth functions for the random effect term and the covariates.
```{r fig.width=12, fig.height=8}
draw(vivax_tvcm, residuals = TRUE)
```
Finlly, we check for concurvity.
```{r}
model_concurvity(vivax_tvcm) %>%
filter(type == "estimate")
```
In the Supplementary Information section of the article there is a further discussion why the concurvity is high in our models.
### P. falciparum
Now, we repeat the GAM fitting and diagnosis for P. falciparum.
```{r message=FALSE}
tic("GAM fitting")
falciparum_tvcm <- bam(
falciparum ~ offset(pop2015_ln) + s(district, bs = "re", k = 49) +
s(time, by = aet, bs = "tp", k = 50) +
s(time, by = prcp, bs = "tp", k = 30) +
s(time, by = tmin, bs = "tp", k = 100),
family = nb(), data = monthly_cases_analysis, method = "fREML", discrete = TRUE
)
toc()
cat("\nConverged?", falciparum_tvcm$converged, "\n")
summary(falciparum_tvcm)
```
```{r fig.width=12, fig.height=8}
appraise(falciparum_tvcm, point_col = "steelblue", point_alpha = 0.4)
```
```{r fig.width=12, fig.height=8}
draw(falciparum_tvcm, residuals = TRUE)
```
```{r}
model_concurvity(falciparum_tvcm) %>%
filter(type == "estimate")
```
# Figure 2
To construct Figure 2 on the article, we first create a data frame with the start and end dates of the PAMAFRO intervention.
```{r message=FALSE, warning=FALSE}
pamafro_period <-
tibble(
start = make_datetime(year = 2005, month = 10, day = 1L),
end = make_datetime(year = 2010, month = 09, day = 1L)
)
```
Then we define a function called `get_est` to extract the smooth estimates evaluated over a range of covariate values in `data` for each model using the `smooth_estimates` of the `gratia` package.
```{r}
get_est <- function(vivax_model, falciparum_model, data) {
vivax_model %>%
smooth_estimates(
smooth = c("s(time):aet", "s(time):prcp", "s(time):tmin"), data = data
) -> vivax_smooth_est
falciparum_model %>%
smooth_estimates(
smooth = c("s(time):aet", "s(time):prcp", "s(time):tmin"), data = data
) -> falciparum_smooth_est
smooth_est_list <- list(
"vivax" = vivax_smooth_est, "falciparum" = falciparum_smooth_est
)
full_smooth_est <-
bind_rows(smooth_est_list, .id = "specie") %>%
mutate(dttm = as_datetime(time))
full_smooth_est
}
```
We create a data frame for the `smooth_estimates` to evaluate over. We need to include all the terms inthe model, but we are going to extract just the estimates for the smooths associated with the covariates `aet`, `prcp` and `tmin`, so it does not matter which values we put in the other terms (`pop2015_ln` and `district`. And since the `smooth_estimates` function evaluates the smooth times the covariate value, that is $s\left(t\right)x$, we fill with ones the values for the covariates, since we just want $s\left(t\right)$.
```{r}
dummy_data <-
tibble(
pop2015_ln = rep(1, 500), district = factor(rep(1, 500)),
time = seq_min_max(monthly_cases_analysis$time, 500), aet = rep(1, 500),
prcp = rep(1, 500), tmin = rep(1, 500)
)
```
Now we use the function we created to extract the smooth estimates.
```{r}
smooth_est <- get_est(vivax_tvcm, falciparum_tvcm, dummy_data)
```
Display the smooth estimates.
```{r}
smooth_est
```
Here, we define a function to plot the smooth estimates and add a PAMAFRO period layer and some labels for the final figure.
```{r}
plot_tve <- function(smooth_est, pamafro_period, labels) {
tve_plot <-
smooth_est %>%
ggplot() +
facet_wrap(
~ by, ncol = 1, scales = "free_y", strip = "left",
labeller = labeller(by = labels)
) +
geom_line(aes(dttm, est, color = specie), size = 1) +
geom_ribbon(
aes(dttm, est, ymin = est + 2*se, ymax = est - 2*se, fill = specie),
alpha = 0.1
) +
geom_rect(
data = pamafro_period, aes(xmin = start, xmax = end), ymin = -100, ymax = 100,
alpha = 0.2
) +
geom_vline(
xintercept = c(pamafro_period$start, pamafro_period$end), linetype = "dashed",
alpha = 0.6
) +
geom_hline(aes(yintercept = 0), alpha = 0.6) +
scale_x_datetime(
date_labels = "%Y", date_breaks = "1 year", expand = expansion(add = 0)
) +
labs(y = NULL, x = NULL) +
theme(
legend.position = "top", legend.title = element_blank(),
strip.placement = "outside", strip.background = element_blank()
) +
scale_color_npg(labels = c("P. vivax", "P. falciparum")) +
scale_fill_npg(labels = c("P. vivax", "P. falciparum"))
tve_plot
}
```
Define the term labels.
```{r}
covariate_labels <- c(
aet = "Actual evapotranspiration\ntime-varying coefficients (linear predictor)",
prcp = "Precipitation\ntime-varying coefficients (linear predictor)",
tmin = "Minimum temperature\ntime-varying coefficients (linear predictor)"
)
```
Plot Figure 2.
```{r fig.width=10, fig.height=9}
plot_tve(smooth_est, pamafro_period, covariate_labels)
```
```{r}
# png(
# filename = "figs/figure-2.png",
# width = 18.5,
# height = 22.5,
# units = "cm",
# pointsize = 12,
# res = 300
# )
#
# tve_plot
#
# dev.off()
```
```{r}
# pdf("figs/figure-2.pdf", width = 6, height = 8)
# tve_plot
# dev.off()
```
# Table 2
```{r}
table_02_sketch = withTags(
table(
class = "display",
thead(
tr(
th(rowspan = 3, "Climate variable"),
th(colspan = 4, "Before"),
th(colspan = 4, "During"),
th(colspan = 4, "After")
),
tr(
lapply(rep(c("Min", "Max"), 3), th, colspan = 2)
),
tr(
lapply(rep(c("Estimate", "95% CI"), 6), th)
)
)
)
)
```
```{r}
smooth_est %>%
mutate(
period = case_when(
dttm < pamafro_period$start ~ "before",
dttm > pamafro_period$end ~ "after",
TRUE ~ "during"
)
) %>%
mutate(period = factor(period, c("before", "during", "after"))) ->
smooth_est_period
```
```{r}
smooth_est_period %>%
group_by(by , period, specie) %>%
slice_max(est, n = 1) %>%
ungroup() -> smooth_est_max
```
```{r}
smooth_est_period %>%
group_by(by, period, specie) %>%
slice_min(est, n = 1) %>%
ungroup() -> smooth_est_min
```
```{r}
smooth_est_extrema_list <- list("max" = smooth_est_max, "min" = smooth_est_min)
```
```{r}
smooth_est_extrema <- bind_rows(smooth_est_extrema_list, .id = "extrema")
```
```{r}
smooth_est_extrema %>%
mutate(ci = sprintf("[%s, %s]", round(est - 2*se, 2), round(est + 2*se, 2))) ->
smooth_est_extrema
```
## P. vivax
```{r message=FALSE}
smooth_est_extrema %>%
filter(specie == "vivax") %>%
select(by, period, extrema, est, ci) %>%
mutate(est = round(est, 4)) %>%
pivot_wider(
by, names_from = c(period, extrema), values_from = c(est, ci), names_sep = "_"
) %>%
select(by, ends_with("min"), ends_with("max")) -> smooth_est_extrema_vivax
```
```{r}
smooth_est_extrema_vivax %>%
column_to_rownames(var = "by") %>%
datatable(
container = table_02_sketch, extensions = 'Buttons',
options = list(
dom = "Bt",
scrollX = TRUE,
columnDefs = list(list(className = 'dt-center', targets = 6)),
buttons = c('copy', 'csv')
),
caption = "P. vivax"
)
```
## P. falciparum
```{r message=FALSE}
smooth_est_extrema %>%
filter(specie == "falciparum") %>%
select(by, period, extrema, est, ci) %>%
mutate(est = round(est, 4)) %>%
pivot_wider(
by, names_from = c(period, extrema), values_from = c(est, ci), names_sep = "_"
) %>%
select(by, ends_with("min"), ends_with("max")) -> smooth_est_extrema_falciparum
```
```{r}
smooth_est_extrema_falciparum %>%
column_to_rownames(var = "by") %>%
datatable(
container = table_02_sketch, extensions = 'Buttons',
options = list(
dom = "Bt",
scrollX = TRUE,
columnDefs = list(list(className = 'dt-center', targets = 6)),
buttons = c('copy', 'csv')
),
caption = "P. falciparum"
)
```
```{r}
smooth_est_period %>%
group_by(period, specie, by) %>%
filter(est == min(est) | est == max(est))
```