A Guide to Using WeightIt for Estimating Balancing Weights

Noah Greifer

2019-09-04

Introduction

WeightIt contains several functions for estimating and assessing balancing weights for observational studies. These weights can be used to estimate the causal parameters of marginal structural models. I will not go into the basics of causal inference methods here. For good introductory articles, see Austin (2011), Austin & Stuart (2015), Robins, Hernan & Brumback (2000), or Thoemmes & Ong (2016).

Typically, the analysis of an observation study might proceed as follows: identify the covariates for which balance is required; assess the quality of the data available, including missingness and measurement error; estimate weights that balance the covariates adequately; and estimate a treatment effect and corresponding standard error or confidence interval. This guide will go through all these steps for two observational studies: estimating the causal effect of a point treatment on an outcome, and estimating the causal parameters of a marginal structural model with multiple treatment periods. This is not meant to be a definitive guide, but rather an introduction to the relevant issues.

Estimating the Effect of a Point Treatment

First we will use the Lalonde dataset to estimate the effect of a point treatment. We’ll use the version of the data set that resides within the cobalt package, which we will use later on as well. Here, we are interested in the average treatment effect on the treated (ATT).

data("lalonde", package = "cobalt")
head(lalonde)

We have our outcome (re78), our treatment (treat), and the covariates for which balance is desired (age, educ, race, married, nodegree, re74, and re75). Using cobalt, we can examine the initial imbalance on the covariates:

library("cobalt")
bal.tab(treat ~ age + educ + race + married + nodegree + re74 + re75,
        data = lalonde, estimand = "ATT", m.threshold = .1)

Based on this output, we can see that most variables are imbalanced in the sense that the standardized mean differences (for continuous variables) and differences in proportion (for binary variables) are greater than .1 for most variables. In particular, re74 and re75 are quite imbalanced, which is troubling given that they are likely strong predictors of the outcome. We will estimate weights using weightit() to try to attain balance on these covariates.

First, we’ll start simple, and use inverse probability weights from propensity scores generated through logistic regression. We need to supply weightit() with the formula for the model, the data set, the estimand (ATT), and the method of estimation ("ps") for propensity score weights).

library("WeightIt")
W.out <- weightit(treat ~ age + educ + race + married + nodegree + re74 + re75,
        data = lalonde, estimand = "ATT", method = "ps")
W.out #print the ooutput

Printing the output of weightit() displays a summary of how the weights were estimated. Let’s examine the quality of the weights using summary(). Weights with low variability are desirable because they improve the precision of the estimator. This variability is presented in several ways: by the ratio of the largest weight to the smallest in each group, the coefficient of variation (standard deviation divided by the mean) of the weights in each group, and the effective sample size computed from the weights. We want a small ratio, a smaller coefficient of variation, and a large effective sample size (ESS). What constitutes these values is mostly relative, though, and must be balanced with other constraints, including covariate balance. These metrics are best used when comparing weighting methods, but the ESS can give a sense of how much information remains in the weighted sample on a familiar scale.

summary(W.out)

These weights have quite high variability, and yield an ESS of close to 100 in the control group. Let’s see if these weights managed to yield balance on our covariates.

bal.tab(W.out, m.threshold = .1, disp.v.ratio = TRUE)

For nearly all the covariates, these weights yielded very good balance. Only age remained imbalanced, with a standardized mean difference greater than .1 and a variance ratio greater than 2. Let’s see if we can do better. We’ll choose a different method: entropy balancing, which guarantees perfect balance on specified moments of the covariates while minimizing the entropy (a measure of dispersion) of the weights.

W.out <- weightit(treat ~ age + educ + race + married + nodegree + re74 + re75,
        data = lalonde, estimand = "ATT", method = "ebal")
summary(W.out)

The variability of the weights has not changed much, but let’s see if there are any gains in terms of balance:

bal.tab(W.out, m.threshold = .1, disp.v.ratio = TRUE)

Indeed, we have achieved perfect balance on the means of the covariates. However, the variance ratio of age is still quite high. We could continue to try to adjust for this imbalance, but if there is reason to believe it is unlikely to affect the outcome, it may be best to leave it as is. (You can try adding I(age^2) to the formula and see what changes this causes.)

Now that we have our weights stored in W.out, let’s extract them and estimate our treatment effect. We’ll use the survey package to incorporate the weights into our analysis.

library("survey")
d.w <- svydesign(ids = ~1, weights = get.w(W.out),
                     data = lalonde)
fit <- svyglm(re78 ~ treat, design = d.w)
coef(fit)

Now let’s do some inference. Although some authors recommend using “robust” sandwich standard errors to adjust for the weights (Robins et al., 2000; Hainmueller, 2012), others believe these can misleading and recommend bootstrapping instead (e.g., Chan, Yam, & Zhang, 2016). We’ll examine both approaches.

svyglm() in the survey package produces robust standard errors. We’ll use the jtools package to provide clean summaries of our results. Similar output can be generated using summary() without installing jtools.

#Robust standard errors and confidence intervals
library("jtools")
summ(fit, confint = TRUE) 

Our confidence interval for treat contains 0, so there isn’t evidence that treat has an effect on re78.

Next let’s use bootstrapping to estimate confidence intervals. We don’t need to use svyglm() and can simply use glm() to compute the effect estimates in each bootstrapped sample because we are not computing standard errors, and the estimated treatment effect estimates will be the same.

#Bootstrapping
library("boot")
est.fun <- function(data, index) {
  W.out <- weightit(treat ~ age + educ + race + married + nodegree + re74 + re75,
        data = data[index,], estimand = "ATT", method = "ebal")
  fit <- glm(re78 ~ treat, data = data[index,], weights = get.w(W.out))
  return(coef(fit)["treat"])
}
boot.out <- boot(est.fun, data = lalonde, R = 999)
boot.ci(boot.out, type = "bca") #type shouldn't matter so much

In this case, our confidence intervals were similar. Bootstrapping can take some time, especially with weight estimation methods that take longer, such as generalized boosted modeling (method = "gbm"), covariate balancing propensity score estimation (method = "cbps"), or entropy balancing with stabilize = TRUE.

If we wanted to produce a “doubly-robust” treatment effect estimate, we could add baseline covariates to the glm() (or svyglm()) model (in both the original effect estimation and the confidence interval estimation).

Estimating the Effect of a Longitudinal Treatment

WeightIt can estimate weights for longitudinal treatment marginal structural models as well. This time, we’ll use the sample data set from twang to estimate our weights. Data must be in “wide” format; to go from long to wide, see the example at ?weightitMSM.

data("iptwExWide", package = "twang")
head(iptwExWide)

We have our outcome variable (outcome), our time-stable baseline variables (gender and age), our pre-treatment time-varying variables (use0, measured before the first treatment, use1, and use2), and our three time-varying treatment variables (tx1, tx2, and tx3). We are interested in the joint, unique, causal effects of each treatment period on the outcome. At each treatment time point, we need to achieve balance on all variables measured prior to that treatment, including previous treatments.

Using cobalt, we can examine the initial imbalance at each time point and overall:

library("cobalt") #if not already attached
bal.tab(list(tx1 ~ age + gender + use0,
             tx2 ~ tx1 + use1 + age + gender + use0,
             tx3 ~ tx2 + use2 + tx1 + use1 + age + gender + use0),
        data = iptwExWide, m.threshold = .1)

bal.tab() indicates significant imbalance on most covariates at most time points, so we need to do some work to eliminate that imbalance in our weighted data set. We’ll use the weightitMSM() function to specify our weight models. The syntax is similar both to that of weightit() for point treatments and to that of bal.tab() for longitudinal treatments. We’ll use method = "ps" for propensity score weights estimated using logistic regression.

Wmsm.out <- weightitMSM(list(tx1 ~ age + gender + use0,
             tx2 ~ tx1 + use1 + age + gender + use0,
             tx3 ~ tx2 + use2 + tx1 + use1 + age + gender + use0),
        data = iptwExWide, method = "ps")
Wmsm.out

No matter which method is selected, weightitMSM() estimates separate weights for each time period and then takes the product of the weights for each individual to arrive at the final estimated weights. Printing the output of weightitMSM() provides some details about the function call and the output. We can take a look at the quality of the weights with summary(), just as we could for point treatments.

summary(Wmsm.out)

Displayed are summaries of how the weights perform at each time point with respect to variability. Next, we’ll examine how well they perform with respect to covariate balance.

bal.tab(Wmsm.out, m.threshold = .1, disp.v.ratio = TRUE, which.time = NA)

By setting which.time = NA in bal.tab(), we can focus on the overall balance assessment, which displays the greatest imbalance for each covariate across time points. We can see that our estimated weights balance all covariates all time points with respect to means and variances. Now we can estimate our treatment effects. We’ll sequentially simplify our model by checking whether interaction terms are needed (implying that specific patterns of treatment yield different outcomes), then by checking whether different coefficients are needed for the treatments (implying that outcomes depend on which treatments are received).

library("survey")
d.w.msm <- svydesign(ids = ~1, weights = get.w(Wmsm.out),
                     data = iptwExWide)
full.fit <- svyglm(outcome ~ tx1*tx2*tx3, design = d.w.msm)
main.effects.fit <- svyglm(outcome ~ tx1 + tx2 + tx3, design = d.w.msm)
anova(full.fit, main.effects.fit)

Based on the non-significant p-value, we don’t have to assume specific treatment patterns yield different outcomes, but rather only that which treatments received or the number of treatments received are sufficient to explain variation in the outcome. Next we’ll narrow down these options by comparing the main effects fit to one that constrains the coefficients to be equal (implying that the cumulative number of treatments received is what matters), as Robins et al. (2000) describe.

cum.fit <- svyglm(outcome ~ I(tx1+tx2+tx3), design = d.w.msm)
anova(main.effects.fit, cum.fit)

Based on the non-significant p-value, we can assume the effects of each treatment are close enough to be treated as the same, indicating that the number of treatments received is the relevant predictor of the outcome. Now we can examine what that treatment effect is with summ() in jtools (or summary()).

summ(cum.fit, confint = TRUE) 

For each additional treatment received, the outcome is expected to decrease by 0.15 points. The confidence interval excludes 0, so there is evidence of a treatment effect in the population.

There is more we can do, as well. We could have fit different types of models to estimate the weights, and we could have stabilized the weights with stabilize = TRUE or by including stabilization factors in our weights using num.formula (see Cole & Hernán, 2008, for more details on doing so). There are other ways of computing confidence intervals for our effect estimates (although model comparison is the most straightforward with the method we used).

References

Austin, P. C. (2011). An Introduction to Propensity Score Methods for Reducing the Effects of Confounding in Observational Studies. Multivariate Behavioral Research, 46(3), 399–424.

Austin, P. C., & Stuart, E. A. (2015). Moving towards best practice when using inverse probability of treatment weighting (IPTW) using the propensity score to estimate causal treatment effects in observational studies. Statistics in Medicine, 34(28), 3661–3679.

Chan, K. C. G., Yam, S. C. P., & Zhang, Z. (2016). Globally efficient non-parametric inference of average treatment effects by empirical balancing calibration weighting. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 78(3), 673–700.

Cole, S. R., & Hernán, M. A. (2008). Constructing Inverse Probability Weights for Marginal Structural Models. American Journal of Epidemiology, 168(6), 656–664.

Hainmueller, J. (2012). Entropy Balancing for Causal Effects: A Multivariate Reweighting Method to Produce Balanced Samples in Observational Studies. Political Analysis, 20(1), 25–46.

Robins, J. M., Hernán, M. Á., & Brumback, B. (2000). Marginal Structural Models and Causal Inference in Epidemiology. Epidemiology, 11(5), 550–560.

Thoemmes, F., & Ong, A. D. (2016). A Primer on Inverse Probability of Treatment Weighting and Marginal Structural Models. Emerging Adulthood, 4(1), 40–59.