|
| 1 | +--- |
| 2 | +title: "Continuous exposures and g-computation" |
| 3 | +format: html |
| 4 | +--- |
| 5 | + |
| 6 | +```{r} |
| 7 | +#| label: setup |
| 8 | +library(tidyverse) |
| 9 | +library(broom) |
| 10 | +library(touringplans) |
| 11 | +library(splines) |
| 12 | +``` |
| 13 | + |
| 14 | +For this set of exercises, we'll use g-computation to calculate a causal effect for continuous exposures. |
| 15 | + |
| 16 | +In the touringplans data set, we have information about the posted waiting times for rides. We also have a limited amount of data on the observed, actual times. The question that we will consider is this: Do posted wait times (`avg_spostmin`) for the Seven Dwarves Mine Train at 8 am affect actual wait times (`avg_sactmin`) at 9 am? Here’s our DAG: |
| 17 | + |
| 18 | +```{r} |
| 19 | +#| echo: false |
| 20 | +#| message: false |
| 21 | +#| warning: false |
| 22 | +library(ggdag) |
| 23 | +
|
| 24 | +coord_dag <- list( |
| 25 | + x = c(wdw_ticket_season = -1, close = -1, weather_wdwhigh = -2, extra_magic_morning = 0, avg_spostmin = 1, avg_sactmin = 2), |
| 26 | + y = c(wdw_ticket_season = -1, close = 1, weather_wdwhigh = 0.25, extra_magic_morning = 0, avg_spostmin = 0, avg_sactmin = 0) |
| 27 | +) |
| 28 | +
|
| 29 | +labels <- c( |
| 30 | + avg_sactmin = "Average actual wait", |
| 31 | + avg_spostmin = "Average posted wait ", |
| 32 | + extra_magic_morning = "Extra Magic Morning", |
| 33 | + wdw_ticket_season = "Ticket Season", |
| 34 | + weather_wdwhigh = "Historic high temperature", |
| 35 | + close = "Time park closed" |
| 36 | +) |
| 37 | +
|
| 38 | +wait_time_dag <- dagify( |
| 39 | + avg_sactmin ~ avg_spostmin + close + wdw_ticket_season + weather_wdwhigh + extra_magic_morning, |
| 40 | + avg_spostmin ~ weather_wdwhigh + close + wdw_ticket_season + extra_magic_morning, |
| 41 | + coords = coord_dag, |
| 42 | + labels = labels |
| 43 | +) |
| 44 | +
|
| 45 | +wait_time_dag |> |
| 46 | + ggdag(use_labels = "label", text = FALSE) + |
| 47 | + theme_void() + |
| 48 | + scale_x_continuous( |
| 49 | + limits = c(-2.25, 2.25), |
| 50 | + breaks = c(-2, -1, 0, 1, 2), |
| 51 | + labels = c("\n(one year ago)", "\n(6 months ago)", "\n(3 months ago)", "8am-9am\n(Today)", "9am-10am\n(Today)") |
| 52 | + ) + |
| 53 | + theme(axis.text.x = element_text()) |
| 54 | +``` |
| 55 | + |
| 56 | +First, let’s wrangle our data to address our question: do posted wait times at 8 affect actual weight times at 9? We’ll join the baseline data (all covariates and posted wait time at 8) with the outcome (average actual time). We also have a lot of missingness for `avg_sactmin`, so we’ll drop unobserved values for now. |
| 57 | + |
| 58 | +You don't need to update any code here, so just run this. |
| 59 | + |
| 60 | +```{r} |
| 61 | +eight <- seven_dwarfs_train_2018 |> |
| 62 | + filter(hour == 8) |> |
| 63 | + select(-avg_sactmin) |
| 64 | +
|
| 65 | +nine <- seven_dwarfs_train_2018 |> |
| 66 | + filter(hour == 9) |> |
| 67 | + select(date, avg_sactmin) |
| 68 | +
|
| 69 | +wait_times <- eight |> |
| 70 | + left_join(nine, by = "date") |> |
| 71 | + drop_na(avg_sactmin) |
| 72 | +``` |
| 73 | + |
| 74 | +# Your Turn 1 |
| 75 | + |
| 76 | +For the parametric G-formula, we'll use a single model to fit a causal model of Posted Waiting Times (`avg_spostmin`) on Actual Waiting Times (`avg_sactmin`) where we include all covariates, much as we normally fit regression models. However, instead of interpreting the coefficients, we'll calculate the estimate by predicting on cloned data sets. |
| 77 | + |
| 78 | +Two additional differences in our model: we'll use a natural cubic spline on the exposure, `avg_spostmin`, using `ns()` from the splines package, and we'll include an interaction term between `avg_spostmin` and `extra_magic_mornin g`. These complicate the interpretation of the coefficient of the model in normal regression but have virtually no downside (as long as we have a reasonable sample size) in g-computation, because we still get an easily interpretable result. |
| 79 | + |
| 80 | +First, let's fit the model. |
| 81 | + |
| 82 | +1.Use `lm()` to create a model with the outcome, exposure, and confounders identified in the DAG. |
| 83 | +2. Save the model as `standardized_model` |
| 84 | + |
| 85 | +```{r} |
| 86 | +_______ ___ _______( |
| 87 | + avg_sactmin ~ ns(_______, df = 5)*extra_magic_morning + _______ + _______ + _______, |
| 88 | + data = seven_dwarfs |
| 89 | +) |
| 90 | +``` |
| 91 | + |
| 92 | +# Your Turn 2 |
| 93 | + |
| 94 | +Now that we've fit a model, we need to clone our data set. To do this, we'll simply mutate it so that in one set, all participants have `avg_spostmin` set to 30 minutes and in another, all participants have `avg_spostmin` set to 60 minutes. |
| 95 | + |
| 96 | +1. Create the cloned data sets, called `thirty` and `sixty`. |
| 97 | +2. For both data sets, use `standardized_model` and `augment()` to get the predicted values. Use the `newdata` argument in `augment()` with the relevant cloned data set. Then, select only the fitted value. Rename `.fitted` to either `thirty_posted_minutes` or `sixty_posted_minutes` (use the pattern `select(new_name = old_name)`). |
| 98 | +3. Save the predicted data sets as`predicted_thirty` and `predicted_sixty`. |
| 99 | + |
| 100 | +```{r} |
| 101 | +_______ <- seven_dwarfs |> |
| 102 | + _______ |
| 103 | +
|
| 104 | +_______ <- seven_dwarfs |> |
| 105 | + _______ |
| 106 | +
|
| 107 | +predicted_thirty <- standardized_model |> |
| 108 | + _______(newdata = _______) |> |
| 109 | + _______ |
| 110 | +
|
| 111 | +predicted_sixty <- standardized_model |> |
| 112 | + _______(newdata = _______) |> |
| 113 | + _______ |
| 114 | +``` |
| 115 | + |
| 116 | +# Your Turn 3 |
| 117 | + |
| 118 | +Finally, we'll get the mean differences between the values. |
| 119 | + |
| 120 | +1. Bind `predicted_thirty` and `predicted_sixty` using `bind_cols()` |
| 121 | +2. Summarize the predicted values to create three new variables: `mean_thirty`, `mean_sixty`, and `difference`. The first two should be the means of `thirty_posted_minutes` and `sixty_posted_minutes`. `difference` should be `mean_sixty` minus `mean_thirty`. |
| 122 | + |
| 123 | +```{r} |
| 124 | +_______ |> |
| 125 | + _______( |
| 126 | + mean_thirty = _______, |
| 127 | + mean_sixty = _______, |
| 128 | + difference = _______ |
| 129 | + ) |
| 130 | +``` |
| 131 | + |
| 132 | +That's it! `difference` is our effect estimate, marginalized over the spline terms, interaction effects, and confounders. |
| 133 | + |
| 134 | +## Stretch goal: Boostrapped intervals |
| 135 | + |
| 136 | +Like propensity-based models, we need to do a little more work to get correct standard errors and confidence intervals. In this stretch goal, use rsample to bootstrap the estimates we got from the G-computation model. |
| 137 | + |
| 138 | +Remember, you need to bootstrap the entire modeling process, including the regression model, cloning the data sets, and calculating the effects. |
| 139 | + |
| 140 | +```{r} |
| 141 | +set.seed(1234) |
| 142 | +library(rsample) |
| 143 | +
|
| 144 | +fit_gcomp <- function(split, ...) { |
| 145 | + .df <- analysis(split) |
| 146 | + |
| 147 | + # fit outcome model. remember to model using `.df` instead of `seven_dwarfs` |
| 148 | + |
| 149 | + |
| 150 | + # clone datasets. remember to clone `.df` instead of `seven_dwarfs` |
| 151 | + |
| 152 | + |
| 153 | + # predict actual wait time for each cloned dataset |
| 154 | +
|
| 155 | + |
| 156 | + # calculate ATE |
| 157 | + bind_cols(predicted_yes, predicted_no) |> |
| 158 | + summarize( |
| 159 | + mean_thirty = mean(thirty_posted_minutes), |
| 160 | + mean_sixty = mean(sixty_posted_minutes), |
| 161 | + difference = mean_sixty - mean_thirty |
| 162 | + ) |> |
| 163 | + # rsample expects a `term` and `estimate` column |
| 164 | + pivot_longer(everything(), names_to = "term", values_to = "estimate") |
| 165 | +} |
| 166 | +
|
| 167 | +gcomp_results <- bootstraps(seven_dwarfs, 1000, apparent = TRUE) |> |
| 168 | + mutate(results = map(splits, ______)) |
| 169 | +
|
| 170 | +# using bias-corrected confidence intervals |
| 171 | +boot_estimate <- int_bca(_______, results, .fn = fit_gcomp) |
| 172 | +
|
| 173 | +boot_estimate |
| 174 | +``` |
| 175 | + |
| 176 | +*** |
| 177 | + |
| 178 | +# Take aways |
| 179 | + |
| 180 | +* To fit the parametric G-formula, fit a standardized model with all covariates. Then, use cloned data sets with values set to each level of the exposure you want to study. |
| 181 | +* Use the model to predict the values for that level of the exposure and compute the effect estimate you want |
0 commit comments