Skip to content

Instantly share code, notes, and snippets.

@malcolmbarrett
Last active July 21, 2020 18:58
Show Gist options
  • Save malcolmbarrett/1511a6d1b85d34a52bdcfab60b158bff to your computer and use it in GitHub Desktop.
Save malcolmbarrett/1511a6d1b85d34a52bdcfab60b158bff to your computer and use it in GitHub Desktop.
library(tidyverse)
library(broom)
library(rsample)
# remotes::install_github("malcolmbarrett/cidata")
library(cidata)
# fit ipw model for a single bootstrap sample
fit_ipw <- function(split, ...) {
# get bootstrapped data sample
.df <- analysis(split)
# fit propensity score model
propensity_model <- glm(
qsmk ~ sex +
race + age + I(age^2) + education +
smokeintensity + I(smokeintensity^2) +
smokeyrs + I(smokeyrs^2) + exercise + active +
wt71 + I(wt71^2),
family = binomial(),
data = .df
)
# calculate inverse probability weights
.df <- propensity_model %>%
augment(type.predict = "response", data = .df) %>%
mutate(wts = 1 / ifelse(qsmk == 0, 1 - .fitted, .fitted))
# fit ipw model
lm(wt82_71 ~ qsmk, data = .df, weights = wts) %>%
tidy()
}
# fit ipw model to bootstrapped samples
ipw_results <- bootstraps(nhefs_complete, 1000, apparent = TRUE) %>%
mutate(results = map(splits, fit_ipw))
# get t-statistic-based CIs
int_t(ipw_results, results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment