-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter_09.qmd
611 lines (472 loc) · 32 KB
/
chapter_09.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
---
title: "Dealing with missing data"
authors:
- name: Johanna Munoz
affiliations:
- ref: julius
- name: Thomas Debray
orcid: 0000-0002-1790-2719
affiliations:
- ref: smartdas
affiliations:
- id: smartdas
name: Smart Data Analysis and Statistics B.V.
city: Utrecht
- id: julius
name: Julius Center for Health Sciences and Primary Care
city: Utrecht
format:
html:
toc: true
number-sections: true
execute:
cache: true
bibliography: 'https://api.citedrive.com/bib/0d25b38b-db8f-43c4-b934-f4e2f3bd655a/references.bib?x=eyJpZCI6ICIwZDI1YjM4Yi1kYjhmLTQzYzQtYjkzNC1mNGUyZjNiZDY1NWEiLCAidXNlciI6ICIyNTA2IiwgInNpZ25hdHVyZSI6ICI0MGFkYjZhMzYyYWE5Y2U0MjQ2NWE2ZTQzNjlhMWY3NTk5MzhhNzUxZDNjYWIxNDlmYjM4NDgwOTYzMzY5YzFlIn0=/bibliography.bib'
---
```{r}
#| include: FALSE
library(kableExtra)
library(table1)
```
## Main Analysis
The main objective of this analysis is to assess whether the number of episodes (y) occurring within specific time periods (years) differs between the treatment groups (1: DMF and 0: TERI). To address potential confounding factors, the researchers consider variables such as patient age, the log of premedical cost (`logPremedicalcost`), previous DMT efficacy (`prevDMTefficacy`), and the number of episodes in previous relapses (prerelapseNum).
When estimating treatment effects from observational data, an assumption is made that the patient populations in both treatment groups are as similar as possible. Various methods for balancing data across treatment groups are proposed, including matching, inverse propensity weighting, stratification, and regression adjustment.
In this case, the focus is specifically on the matching method, which offers advantages over regression adjustment by potentially alleviating issues related to model mis-specification. This includes addressing non-linear relationships between certain confounders and the outcome variable and accounting for treatment effects that may depend on specific confounders (treatment-confounder interaction terms). Propensity scores are used to match subjects in the treatment groups.
Moreover, intentionally introducing incomplete covariate variables in this example adds complexity to the propensity score estimation. Depending on the propensity score estimation technique employed, it may be necessary to incorporate an imputation step. For instance, logistic regression estimation requires complete data for all observations, while XGBoost is robust to missing data \cite{zhao_propensity_2021}.
To estimate marginal treatment effects, the g-computation method is employed \cite{snowden_implementation_2011}. This method involves specifying a model for the outcome dependent on the treatment and covariates. The potential outcomes, i.e., the predicted values of the outcome on treatment ($y_i^1$) and control ($y_i^0$) for each sample unit $i$, are estimated. The marginal treatment effect is then calculated by contrasting the averaged estimated potential outcomes.
In this example, we consider the estimation of comparative treatment effects in the absence of treatment-effect heterogeneity.
## Estimation workflow
The proposed workflow consists of the following steps:
![Estimation Workflow](resources/chapter 09/Workflow.png)
1. **Data Exploration:** In this step, we examine the observed data to comprehend the variables within the dataset. Our primary focus lies on identifying missing patterns and relationships among observed variables, including missing indicator variables and others. This exploration aids in discerning the most plausible missing mechanisms and suitable imputation techniques. Additionally, field experts' insights may be incorporated to enhance understanding of the missing process, potentially considering MNAR assumptions.
2. **Imputation:** It is essential to evaluate whether the imputation procedure is necessary or if simpler methods, such as complete case analysis, are more suitable. In case imputation procedures are required, selecting plausible imputation methods that align with the main model analysis is crucial. This involves choosing individual imputation methods for each incomplete variable, determining the predictor variables on the imputation model. Pre_imputation (where imputation values can be deterministically derived from other variables) and Post-imputation (e.g.ensuring imputed values fall within a reasonable range) steps may also considered.
3. **Data Balancing:** Several methods, including PS matching or inverse weighting propensity score, can be utilized. It is required to evaluate the balance, which could be done via visual inspection.(eg.cobalt package). In this example, we estimate propensity scores using logistic regression. For most balancing procedures in R, counterparts specifically designed for imputed datasets are available, such as those in the matchthem R package, which includes PS matching and IPW as done in the matchit R package.
4. **Model Fit:** : It is fit a model to predict the outcomes for each sample unit under each possible treatment value (DMF and TERI), as predictors include the treatment and optionally the baseline covariates and also the propensity score.
5. **Treatment Estimation & Pooling:** For simplicity in this tutorial, we will use the comparison functions from the R **matchingmethods** package \cite{arel_marginaleffects_2023}, which can be used for completed data and also from outputs from the imputation process. In the last case, internally the functions calculate the treatment effects on each imputed dataset and pool the estimates using Rubin's Rules.
Let's start by preparing the R environment. All the functions used in this tutorial can be found in the resource file `functions.r`.
```{r}
#| warning: false
#| echo: true
# Load the required packages and additional functions
source("resources/chapter 09/functions.r")
```
## Homogeneous Treatment Effect
In this example, we focus on estimating comparative treatment effects in the absence of heterogeneous treatment effects (HTE).
### Generating an Observational Dataset
We can simulate an observational dataset of $N = 3000$ patients as follows:
```{r hom gendata}
data_hom <- generate_data(n = 3000, seed = 1234)
```
The **generate_data()** function allows the specification of various treatment effect options, easily adjustable by modifying the beta parameter. In this instance, we assume a consistent treatment effect across the entire target population. This dataset currently contains no missing values.
The simulated dataset comprises two treatment groups with variations in baseline characteristics. For example, the figure below illustrates baseline imbalances in covariates such as age.
```{r hom plotdata}
#| fig.width: 6
#| fig.height: 6
#| fig.align: center
#| fig.cap: Figure 1:Distribution of confounders and outcome variable
#| echo: false
fplot <- plot_dis(data = data_hom) #Age density
fplot
```
We can calculate the treatment effect on the complete observed dataset. To do this, we start by balancing the dataset using Propensity Score matching. In this case, the propensity score model uses confounder variables only: `age`, `gender`, `prevDMTefficacy`, `logPremedicalcost`, and `prerelapseNum`.
```{r full1}
## Apply Matching on the PS for the ATE
mF <- matchit(treatment ~ age + gender + prevDMTefficacy +
logPremedicalcost + prerelapseNum,
data = data_hom,
family = binomial,
method = "full",
caliper = 0.2,
estimand = "ATE",
replace = FALSE)
## Extract matched data
mdata <- match.data(mF)
```
Then, we proceed to model estimation. In this case, a Poisson model is used which assumes that $y_i \sim \text{Poisson}(\lambda_i)$. In this expression, $\log(\lambda_i)$ = $\beta_0$ + $\beta_1$ `treatment` + $\beta_2$ `age` + $\beta_3$ `gender` + $\beta_4$ `prevDMTefficacy` + $\beta_5$ `logPremedicalcost` + $\beta_6$ `prerelapseNum` + $\beta_7$ `numSymptoms` + log(`years`)
Since patient measurements were recorded over varying time frames, the natural logarithm of the years of evaluation is incorporated as an offset in the model. The model is fitted with a glm function, and we include the treatment and the baseline covariates as predictors, which are optional if the data is well balanced. Additionally, it is necessary to specify the matching weights in the glm function.
```{r full2}
# Model fit
fit_mod <- glm(as.formula("y ~ treatment + gender + age + logPremedicalcost + prerelapseNum + prevDMTefficacy + numSymptoms + offset(log(years))"),
family = poisson(link = "log"),
data = mdata,
weights = weights)
```
Typically, Poisson models adjust standard errors using robust standard errors to accommodate small values arising from the equidispersion assumption. This correction can be directly applied to the model using the vcovCL() function \cite{zeileis_sandwich_2022}. However, given that we will calculate the treatment effect using the functions of the **marginaleffects** package, this step becomes redundant. This package allows specifying HC3 sandwich standard errors during treatment estimation.
Finally, we calculate the Average Treatment Effect (ATE). The ATE is defined as $$\tau_{ATE}=E(y_i^1-y_i^0)$$
But this cannot be directly extracted from the $\beta_1$ parameter, as the model has $log(\lambda)$ as the response. We estimate it as: $$\tau_{ATE}=E(\lambda^1_i-\lambda^0_i)$$ This can be done with the function **avg_comparisons()**, from the R package marginaleffect, that calculates the potential outcomes for each unit sample and then combines them to summarize the average effect.
```{r full3}
# Estimation of treatment effects with robust standard errors
ATE <- avg_comparisons(fit_mod,
variables = list(treatment = c("TERI","DMF")),
vcov = "HC3",
newdata = mdata,
wts = "weights")
result_ATE <- data.frame( ATE,
analysis = "Full Data")
```
Henceforth, for ease of explanation, we will use the function **TE_estimation()** attached to the function code that performs all the previous estimation steps at once.
### Generating Missing Values
In this example, we focus on the case where confounder variables are incomplete.
Missing values can be generated using the **getmissdata()** function, considering the following patterns of missingness for the log previous medical cost (`logPremedicalcost`):
1. MAR: missingness depends on `age` and `sex`
2. MART: missingness depends on `age`, `sex` and the treatment variable `treatment`
3. MARTY: missingness depends on `age`, `sex`, `treatment` and the outcome variable `y`
4. MNAR: missingness depends on `age`, `sex` and `logPremedicalcost`
Lets select the missing data pattern "MART"
```{r hom miss}
m_data_hom <- get_missdata(data = data_hom, scenario = "MART")
```
After introducing missing values, we only have complete data for $N=$ `r sum(complete.cases(m_data_hom))` patients.
```{r hom misstable}
#| echo: false
dat <- formatMSdata(m_data_hom)
table1(~ age + gender + prevDMTefficacy + logPremedicalcost + numSymptoms + prerelapseNum | treatment, data = dat, caption = "Baseline characteristics of the incomplete dataset.")
```
### Data Exploration
First, let's examine the missing patterns in our dataset. This will help us better understand the missing data, including the proportion of missing values and the underlying causes, which may be related to other observable variables. Various R packages, such as ggmice, vim, naniar, and factorminer, can assist in visualizing the data.
Upon initial examination, we've observed that the outcome variable `y`, treatment status, and gender are fully observed, while other covariate variables, including age, logPremedicalcost, prevDMTefficacy, numSymptoms, and prerelapseNum, have incomplete data. In total, approximately 11% of the observations in the dataset have missing data. These missing values follow a non-monotonic pattern, requiring the use of MCMC imputation techniques, therefore we mainly use the Full Conditional Specification approach given in the mice package.
When assessing missingness based on treatment groups, we find that there are more patients receiving DMF treatment. However, the percentage of missing values is higher for the DMF treatment group compared to the TERI treatment group, indicating that data is unlikely to be MCAR when the proportion of missing differs by treatment allocation.
```{r hom miss exploration}
library(naniar)
naniar::gg_miss_upset(m_data_hom, nsets = 10)
naniar::gg_miss_var(m_data_hom, facet = treatment, show_pct = T)
```
Additionally, it could be explored whether associations exist between the missingness of variables and other observed variables, indicating if a MAR assumption is more plausible than a MCAR assumption. The plausibility of MNAR vs. MAR assumptions cannot be evidenced by observable data, and the possibility of a MNAR scenario is contemplated based on expert input.
### Methods for Handling Missing Data
#### Complete Case Analysis
To estimate the ATE using propensity score matching, we employ complete case analysis. Initially, we filter out all units with incomplete data and then apply the estimation process as before.
```{r hom cc}
#| message: false
#| warning: false
# Filter out the complete case data
ccdata <- m_data_hom[complete.cases(m_data_hom), ]
# Estimation procedure
result_CC <- ATE_estimation( data = ccdata,
analysis = "Complete Case Analysis")$ATE
result_ATE <- result_ATE %>% add_row(result_CC)
```
#### Missing Indicator
In this method, it is essential to create missing indicators and deterministic imputed variables for each incomplete variable. For example, for the "age" variable, we calculate a missing indicator, denoted as "age.mind," and a deterministic imputed value of age where missing values are replaced by an arbitrary value (in this case, the missing values were replaced by zero).
```{r hom mind}
#| eval: false
dat$age.mind <- ifelse( is.na(dat$age),1,0) # missing indicator of age
dat$age <- ifelse(is.na(dat$age), 0, dat$age) # deterministic imputed age,
```
Subsequently, the Propensity Score (PS) model is estimated for all the confounding variables, including their missing indicators. In this case, the propensity score model is given by:
```{r hom mind1}
#| eval: false
PS.formula <- treatment ~ gender + age.mind + age + lpmc.mind +
logPremedicalcost + pde.mind + prevDMTefficacy + prn.mind + prerelapseNum
```
Then, the estimation process follows the same structure as before:
```{r hom mind2}
#| eval: false
result_mind <- ATE_estimation(data = m_data_hom, PSform = "Mind",
analysis = "Missing indicator")$ATE
result_ATE <- result_ATE %>% add_row(result_mind)
```
#### Multiple Imputation
In this section, we will generate $m=10$ imputed datasets and perform matching within each imputed dataset. We first need to specify the imputation model for `prevDMTefficacy`, `premedicalcost`, `numSymptoms`, `prerelapseNum`, and `age`, i.e., the predictors for each incomplete variable. This can be done in mice via the prediction matrix or by using the form parameter where the models are specified for each variable and saved in a list.
```{r hom imp1}
#| message: false
#| warning: false
# We add a covariate for log(years)
impdata <- m_data_hom %>% mutate(logyears = log(years))
# Specify the conditional imputation models
form_y <- list(prevDMTefficacy ~ age + gender + logyears + logPremedicalcost +
numSymptoms + treatment + prerelapseNum + y,
logPremedicalcost ~ age + gender + logyears + prevDMTefficacy +
numSymptoms + treatment + prerelapseNum + y,
numSymptoms ~ age + gender + logPremedicalcost + logyears +
prevDMTefficacy + prerelapseNum + treatment + y,
prerelapseNum ~ age + gender + logPremedicalcost + logyears +
prevDMTefficacy + numSymptoms + treatment + y,
age ~ prerelapseNum + gender + logPremedicalcost + logyears +
prevDMTefficacy + numSymptoms + treatment + y)
form_y <- name.formulas(form_y)
```
Next, we need to set the individual imputation model for each variable. We call the mice function, which automatically proposes certain imputation methods according to the type of variable. Here, we decide to modify the imputation method for the `numSymptoms` and `prevDMTefficacy` variables to the predictive mean matching method "pmm". After this, we run the **mice()** function to generate 10 imputed datasets.
```{r hom imp2}
#| message: false
#| warning: false
# Adopt predictive mean matching for imputing the incomplete variables
imp0 <- mice(impdata, form = form_y, maxit = 0)
method <- imp0$method
method["numSymptoms"] <- "pmm"
method["prevDMTefficacy"] <- "pmm"
# Generate 10 imputed datasets
imp <- mice(impdata, form = form_y, method = method, m = 100, maxit = 20,
printFlag = FALSE)
```
Before proceeding with the estimation procedure, we inspect the convergence of all the imputed variables using a trace plot:
```{r homimp convergency}
plot(imp)
```
We can also inspect these plots using **ggmice**:
```{r homimp convergency_ggmice}
#| message: false
#| warning: false
require(ggmice)
plot_trace(imp, c("age", "numSymptoms",
"logPremedicalcost", "prerelapseNum", "prevDMTefficacy"))
```
As there don't seem to be any problems in the trace plot (i.e., no marked tendency & well-dispersed plots), we can now proceed with the PS Matching in each of the imputed datasets using the **MatchedThem** package functions. Here, we adopt full matching without replacement and use a logistic model. The function allows the pooling of PS estimates, which can be done through the within or across approach.
##### Multiple Imputation (within approach)
The within approach it is specified with the approach parameter in the matchthem function as follows:
```{r hom miw}
#| message: false
# Matching based on PS model
mdata <- matchthem(formula = treatment ~ age + gender+ prevDMTefficacy +
logPremedicalcost + prerelapseNum,
datasets = imp,
approach = "within",
method = "full",
caliper = 0.1,
family = binomial,
estimand = "ATE",
distance = "glm",
link = "logit",
replace = FALSE)
```
Then we proceed to fit a main model on the outcome Y.
```{r hom miw2}
#| message: false
# Get a list of the imputed datasets
dat <- complete( mdata, action = "all")
# Fit the model on each imputed dataset
mod <- lapply(dat, \(i)
glm(formula = as.formula("y ~ treatment + gender + age + logPremedicalcost + prerelapseNum + prevDMTefficacy + numSymptoms + offset(log(years))"),
family = poisson(link = "log"),
weights = weights,
data = i))
```
Finally, we utilize the marginal effects package to estimate the treatment effect. As before, we use the `avg_comparisons` function, which allows us to specify the variance correction. While most of the marginal effects functions are designed to handle imputed datasets, since we need to evaluate the model on each imputed dataset, we manually pass each imputed dataset into the parameter newdata using the lapply function, as follows:
```{r hom miw3}
#| message: false
#| warning: false
#| echo: false
# Calculate the treatment effect on each imputed dataset
ATE_i <- lapply(seq_along(mod), \(i)
avg_comparisons(mod[[i]],
variables = list(treatment = c("TERI","DMF")),
vcov = "HC3",
wts = "weights",
newdata = dat[[i]]))
# Pool the estimates with rubins rules
result_micew <- data.frame(summary(mice::pool(ATE_i), conf.int = TRUE)) %>%
rename('conf.low' = "X2.5..",'conf.high' = "X97.5..") %>%
mutate(analysis = "MICE (within)")
result_ATE <- bind_rows(result_ATE,result_micew)
```
##### Multiple Imputation (across aproach)
We proceed similarly as before; the only difference is specifying the approach "across" in the matchthem function. To simplify the steps, use the built-up function ATE_estimation.
```{r hom mia1}
#| message: false
#| warning: false
result_micea <- ATE_estimation( data = imp,
approach = "across",
analysis = "MICE (across)")$ATE
result_ATE <- bind_rows(result_ATE, result_micea)
```
### Results
Analysis methods:
- **Full Data**: The treatment effect is estimated in the original data of $N=3000$ patients where no missing values are present. This estimate can be used as a benchmark to compare the missing data methods.
- **Complete Case Analysis**: The treatment effect is estimated using all data from $N=$ `r sum(complete.cases(m_data_hom))` patients that do not have any missing values.
- **Missing Indicator**: The treatment effect is estimated in the incomplete dataset of $N=3000$ patients. The propensity score model includes a missing indicator variable for each incomplete covariate.
- **MICE**: A treatment effect is estimated within each imputed dataset using propensity score analysis. Using Rubin's rule, the ten treatment effects are combined into a single treatment effect.
```{r hom fres}
#| message: false
#| warning: false
library(ggplot2)
result_ATE$analysis = factor(result_ATE$analysis,
levels = c("Full Data",
"Complete Case Analysis",
"Missing indicator",
"MICE (within)",
"MICE (across)"))
ggplot(result_ATE,aes(x = analysis, y = estimate, col = analysis)) +
geom_point(shape = 1,
size = 1) +
geom_errorbar(aes(ymin = conf.low ,
ymax = conf.high),
width = 0.2,
size = 0.5) +
see::scale_color_flat() + theme_light() +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
legend.position = "bottom")
```
In this example, we observe that there is no significant difference across the methods. The Complete Case Analysis yields a wider confidence interval and leads to more biased estimates. It appears that the MICE method with the within approach and Missing Indicator methods provide less biased estimates. However, the formal leads to a non-significant treatment estimate similar to the results from the Full Dataset.
## Heterogeneous Treatment Effect
In practice, the treatment effect is often not homogeneous among individuals. In this section, we will consider a heterogeneous treatment effect where there is effect modification by the confounding covariates.
The way we generate the heterogeneous dataset is to segment the population according to the efficacy of each treatment (**Iscore**). We can see in the graph below, that for the previous dataset, there was no difference in treatment effect across the groups, but in this new dataset, we observe a marked difference across groups.
Let's start by simulating a new heterogeneous treatment dataset, using the same missing data generation process as before.
```{r het}
#| echo: false
# Save the results
data_het <- generate_data(n = 3000, beta = c(log(0.3), log(0.5), log(1),
log(1.1), log(1.5)), seed = 1234)
m_data_het <- get_missdata(data = data_het, scenario = "MART")
ggpubr::ggarrange(Relapserate_plot0(data = data_hom),
Relapserate_plot0(data = data_het),
labels = c("Homogeneous","Heterogeneous"),
common.legend = TRUE, legend = "bottom")
```
A summary of the complete data is given below
```{r}
#| echo: false
#| warning: false
df.tbl <- m_data_het %>% mutate(premedicalcost = exp(logPremedicalcost))
label(df.tbl$age) <- "Age"
units(df.tbl$age) <- "years"
label(df.tbl$gender) <- "Gender"
label(df.tbl$prerelapseNum) <- "Previous number of relapses"
label(df.tbl$prevDMTefficacy) <- "Efficacy of previous disease modifying therapy"
label(df.tbl$premedicalcost) <- "Previous medical cost (USD)"
units(df.tbl$premedicalcost) <- "\\$"
label(df.tbl$numSymptoms) <- "Previous number of symptoms"
table1(~ age + gender + prerelapseNum + prevDMTefficacy + premedicalcost + numSymptoms | treatment, data = df.tbl, caption = "Baseline characteristics of the case study data")
```
We use also the G computation to calculate the treatment effect, but this time in the main model, we take into account the interaction of the treatment and the covariates. In addition, we will estimate the conditional average treatment effect given the Iscore groups.
$$\tau_{CATE}(x) =E(y^1-y^0|X=x)$$
```{r hetfull}
het.model <- "y ~ treatment*(gender + age + logPremedicalcost + prerelapseNum + prevDMTefficacy + numSymptoms) + offset(log(years))"
result_het <- ATE_estimation (data = data_het,
model = het.model,
analysis = "Full data",
variable = "Iscore")$ATE_var
```
### Methods for Dealing with Missing Data
#### Complete Case Analysis
As before, we also proceed to calculate the ATE by employing the Complete Case Analysis.
```{r hetcc}
result_CC <- ATE_estimation(data = m_data_het[complete.cases(m_data_het),],
model = het.model,
analysis = "Complete Case Analysis",
variable = "Iscore")$ATE_var
result_het <- bind_rows(result_het,result_CC)
```
#### Multiple Imputation by Treatment Group
As there is a treatment effect, the first imputation approach that we consider is to perform a separate imputation procedure on each of the treatment groups. This is an option that can be implemented in this case as the treatment group is complete, and the sample size is large enough in each treatment group \cite{zhang_should_2023}. Here we use the same imputation models that we used before but removing the treatment variable.
```{r het sep}
#| message: false
#| warning: false
#| results: hide
imp_het <- m_data_het %>% mutate(logyears = log(years))
data_DMF <- subset(imp_het, treatment == "DMF")
data_TERI <- subset(imp_het, treatment == "TERI")
imp_DMF <- mice(data_DMF, form = form_nt,method = method, m = 10,
maxit = 10, printFlag = FALSE)
imp_TERI <- mice(data_TERI,form = form_nt,method = method, m = 10,
maxit = 10, printFlag = FALSE)
imp_sep <- rbind(imp_DMF, imp_TERI)
```
#### Parametric Multiple Imputation
As the main model includes treatment interaction terms, we need to include them also in the imputation model to avoid congeniality issues. So we modify the imputation models for each variable, including the treatment interaction terms and also the interaction of treatment and outcome as follows:
```{r hetmi}
form_iy <- list(prevDMTefficacy ~ (y + treatment)*(age + gender + logPremedicalcost + numSymptoms + prerelapseNum + logyears) + y*treatment,
logPremedicalcost ~ (y + treatment)*(age + gender + prevDMTefficacy + numSymptoms + prerelapseNum + logyears) + y*treatment,
numSymptoms ~ (y + treatment)*(age + gender + logPremedicalcost + prevDMTefficacy + prerelapseNum + logyears) + y*treatment,
prerelapseNum ~ (y + treatment)*(age + gender + logPremedicalcost + prevDMTefficacy + numSymptoms + logyears) + y*treatment,
age ~ (y + treatment)*(prerelapseNum + gender + logPremedicalcost + prevDMTefficacy + numSymptoms + logyears) + y*treatment)
form_iy <- name.formulas(form_iy)
```
Then we proceed to impute the dataset with mice with a parametric model using and not the interaction terms.
```{r hetmi2}
#| message: false
#| warning: false
#| results: hide
impdata_het <- m_data_het %>% mutate(logyears = log(years))
imp_y <- mice(impdata_het, form = form_y, method = method, m = 10,
maxit = 10, printFlag = FALSE)
imp_iy <- mice(impdata_het, form = form_iy, method = method, m = 10,
maxit = 10, printFlag = FALSE)
```
#### Non-parametric Multiple Imputation
Another option is to use imputation methods based on non-parametric approaches such as random forest, which are robust to the inclusion of interaction and quadratic terms. Here we use the "rf" method included in mice, but there are other available options as discussed by \cite{shah_comparison_2014}.
```{r het rf}
#| message: false
#| warning: false
#| results: hide
imp_rf <- mice(impdata_het, method = "rf", m = 10, maxit = 10,
ntree = 10, printFlag = FALSE)
#plot(imp_rf)
```
It has also been proposed a new method based on XGBoost that seems also an option for data with interaction terms \cite{deng_multiple_2023}. Here it is required to calibrate the parameters to be included in the function and do an extra job to put it in the mice package format.
```{r het gb}
#| message: false
#| warning: false
#| results: hide
library(mixgb)
params <- list(max_depth = 3, subsample = 0.7, nthread = 2)
cv.results <- mixgb_cv(data = impdata_het, nrounds = 100,
xgb.params = params, verbose = FALSE)
imp_gb <- mixgb(data = impdata_het, m = 10, maxit = 10, nrounds = cv.results$best.nrounds)
data_gb <- bind_rows(impdata_het,imp_gb, .id = '.imp')
data_gb$'.imp' <- as.numeric(data_gb$'.imp') - 1
imp_gb <- mice::as.mids(data_gb)
```
After checking the convergence of all the imputation methods,via traceplots, we proceed to estimate the treatment effect with the **ATE_estimation()** function, were it is required to specify the variable *Iscore* to evaluate the treatment effect on each group.
```{r het all}
#| message: false
#| warning: false
#| results: hide
imp_datasets <- list(imp_sep,imp_y,imp_iy,imp_rf,imp_gb)
n_analysis <- c("MICE (separated)",
"MICE (no interaction)",
"MICE (interaction)",
"Random forest",
"MixGb")
response_imp <- lapply(seq_along(imp_datasets), \(i)
ATE_estimation( data = imp_datasets[[i]],
model = het.model,
approach = "within",
variable = "Iscore",
analysis = n_analysis[[i]])$ATE_var)
response_imp <- do.call(rbind,response_imp)
result_het <- bind_rows(result_het,response_imp)
```
### Results
```{r het plot}
#| message: false
#| warning: false
library(ggplot2)
result_het$Iscore <- as.factor(result_het$Iscore)
levels(result_het$Iscore) <- c("High DMF",
"Moderate DMF",
"Neutral",
"Moderate TERI",
"High TERI")
result_het$analysis = factor(result_het$analysis,
levels = c("Full data",
"Complete Case Analysis",
"MICE (separated)",
"MICE (no interaction)",
"MICE (interaction)",
"Random forest",
"MixGb"))
ggplot(result_het,aes(x = analysis, y = estimate, col = analysis)) +
geom_point(shape = 1,
size = 1) +
geom_errorbar(aes(ymin = conf.low,
ymax = conf.high),
width = 0.2,
size = 0.5) +
see::scale_color_flat() + theme_light() +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
legend.position = "bottom") +
facet_wrap("Iscore",ncol = 2, scales = "free")
```
We found that except for the complete case analysis, all the methods lead to unbiased results of the treatment effect across all the Iscore groups. However, it seems that the estimation of the MixGb method leads to estimations closer to the Full dataset ones.
## Version info {.unnumbered}
This chapter was rendered using the following version of R and its packages:
```{r}
#| echo: false
#| message: false
#| warning: false
sessionInfo()
```
## References {.unnumbered}