-
Notifications
You must be signed in to change notification settings - Fork 6
/
day8_stratification_balance.Rmd
1030 lines (796 loc) · 37 KB
/
day8_stratification_balance.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
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: |
| Statistical Adjustment and Assessment of Adjustment in Observational Studies
date: '`r format(Sys.Date(), "%B %d, %Y")`'
author: |
| ICPSR 2023 Session 1
| Jake Bowers \& Tom Leavitt
bibliography:
- 'BIB/MasterBibliography.bib'
- 'BIB/master.bib'
- 'BIB/misc.bib'
- 'BIB/refs.bib'
fontsize: 10pt
geometry: margin=1in
graphics: yes
biblio-style: authoryear-comp
colorlinks: true
biblatexoptions:
- natbib=true
output:
beamer_presentation:
slide_level: 2
keep_tex: true
latex_engine: xelatex
citation_package: biblatex
template: icpsr.beamer
incremental: true
includes:
in_header:
- defs-all.sty
md_extensions: +raw_attribute-tex_math_single_backslash+autolink_bare_uris+ascii_identifiers+tex_math_dollars
pandoc_args: [ "--csl", "chicago-author-date.csl" ]
---
<!-- To show notes -->
<!-- https://stackoverflow.com/questions/44906264/add-speaker-notes-to-beamer-presentations-using-rmarkdown -->
```{r setup1_env, echo=FALSE, include=FALSE}
library(here)
source(here::here("rmd_setup.R"))
```
```{r setup2_loadlibs, echo=FALSE, include=FALSE}
## Load all of the libraries that we will use when we compile this file
## We are using the renv system. So these will all be loaded from a local library directory
library(dplyr)
library(ggplot2)
library(coin)
library(RItools)
library(optmatch)
```
## Today
1. Agenda: The problem of covariance adjustment to reduce "bias"/
confounding. **How can we answer the question about whether we have
adjusted enough and avoided extrapolation and dependence on functional
form?**
a. A simple approach: stratification on one categorical variable
(using weighted combinations of within-strata estimates for an overall
estimate). Justify this **design** by comparison of this stratification
with one or more **standards** of unconfounded designs (like an experiment
with treatment randomized within strata).
b. A more complex approach: find
sets that are as similar as possible in terms of a continuous variable
(bipartite matching). Balance assessment after stratification.
2. Recap: Problems of using linear (or
other parametric models) for **adjustment** (as well as statistical
inference) include justifying variables, justifying functional forms (of
$x_1 \rightarrow Z$ and $x_1 \rightarrow Y$ and $x_1 \rightarrow x_2$, and
$f(x_1,x_2) \rightarrow Y$ and $f(x_1,x_2) \rightarrow Z$ and $f(x_1,x_2)
\rightarrow x_3$, diagnosing extrapolation and interpolation, diagnosing
and confronting overly influential points, and struggling with the
problems of seeing the causal estimate and test results everytime you try
a new specification. And, basically, finding a **standard of adjustment**
for such models where we can answer the question "have we adjusted
enough"?
3. Questions arising from the reading or assignments or life?
# Strategies for Causal Inference
## Strategies and Workflow for randomized studies
### Before fielding the study
- Plan the design for interpretability and power.
- Pre-register your analysis plan and experimental design.
### After outcome data have been collected
- Make the case that randomization worked. (often trivial, but in field
experiments with long chains of responsibility, an important screening step
even if not dispositive of a "failed experiment").
- Increase precision with design and test statistics (and even models of
effects)
- Make sure that your estimator is estimating the right thing (i.e. is not
biased or at least is consistent)
- Make sure that your test has a controlled false positive rate and is as
powerful as possible (i.e. the coverage rate of a confidence interval is
nominal, the Type I error rate is controlled).
## Strategies for Adjustment of Observational Studies
- If you have randomized $Z$ but not $D$, then IV. (Like an observational study within an experiment.)
- Find a discontinuity/A Natural Experiment (RDD: either natural experiment
or continuous forcing function)
- Multiple controls each with different biases (i.e. "Choice as an alternative to control"
see [@rosenbaum:1999])
- "Controlling For" directly in linear models, but lots of questions to answer...
- Difference in Differences (if you have some pre- and post-outcomes)
- Matched Stratification (approximating a block-randomized experiment)
- Best matched subset selection (approximating a completely or simply
randomized experiment)
- Weighting (the stratification approaches imply weightings, so we could try to calculate good weightings directly)
- Direct theoretical modeling / Directed Acyclic Graphs (DAGS) to guide other
data modeling choices.
# Recap
## Regression is not research design {.shrink}
What does this mean?
Research design occurs **before** estimation and testing. You can try out lots
of ideas, simulate, discuss, pre-register your planned analysis and your
design, all before you produce the estimate or test having to do with some
causal effect. This means (1) you are not seeing the estimates and tests when
you are looking for a good design and (2) standards for good design are not the
same as the standards for good estimators and tests.
When you present the result of a regression model after searching for a
specification, readers wonder:
1. is this just the best result out of
thousands? Are most results like this? Or was this cherry picked?
2. how many
$p$-values were looked at before reporting this one with $p < .05$?
\small{Recall
that if we reject $H_0$ when $p < .05$, we are saying that it is ok for 5% of
tests to mislead us --- to have $p < .05$ when there is no effect (when $H_0$
is true). So, a $p < .05$ after one test means that either have a rare testing
error (a false positive result) or that $H_0$ is false. But an unadjusted $p < .05$ after 100 tests is virtually
certain to occur (with prob of .99) when $H_0$ is true: $p < .05$ is a signal of a false positive error not of a substantive signal about $H_0$. So we
should not reject the null even if the $p < .05$ in this case. (See
[EGAP Guide on Multiple Comparisons](https://egap.org/resource/10-things-to-know-about-multiple-comparisons/) ).
}
## Regression is not research design
Say we want to describe the relationship between an outcome $y$, a focal explanatory
variable, $z$ and a potential confounder $x$ as a linear and additive function:
$y_i = \beta_0 + \beta_1 z_i + \beta_2 x_i$. What can we say about this?
1. "The **math implies** that the difference in $y$ between any two values of $z$ that differ by 1 must be the same regardless of which two values and regardless of the values that we plug-in for $x$." (Correct)
2. "The **math says** that relationship between differences in $z$ and differences in $y$ ($\frac{dy}{dz}$), is the same for all values of $z$ and $x$. This is a constant relation." (Correct)
## Regression is not research design
Say we fit that mathematical model, $y_i = \beta_0 + \beta_1 z_i + \beta_2 x_i$, to data. What can we say?
```{r, echo=FALSE, out.width=".5\\textwidth"}
load(here::here("day7_dat.rda"))
lm_Y_x1 <- lm(Y ~ x1, data = dat)
lm_Z_x1 <- lm(Z ~ x1, data = dat)
dat$resid_Y_x1 <- resid(lm_Y_x1)
dat$resid_Z_x1 <- resid(lm_Z_x1)
lm2 <- lm(Y~Z+x1,data=dat)
coef(lm2)
```
Here is a plot of Y-without-linear-x1 on X-without-linear-x1 with a slope of `r coef(lm2)[["Z"]]`.
```{r, echo=FALSE, out.width=".5\\textwidth",warning=FALSE}
g1 <- ggplot(dat,aes(x=resid_Z_x1,y=resid_Y_x1,color=x1))+geom_point()+geom_smooth(method="lm",se=FALSE)
print(g1)
```
## Regression is not research design {.shrink}
```{r, echo=FALSE, out.width=".8\\textwidth",warning=FALSE}
g2 <- ggplot(dat,aes(x=x1,y=Y,color=factor(Z)))+geom_point()+
geom_abline(intercept=coef(lm2)[["(Intercept)"]],slope=coef(lm2)[["x1"]])+
geom_abline(intercept=(coef(lm2)[["(Intercept)"]]+coef(lm2)[["Z"]]),
slope=coef(lm2)[["x1"]],color="turquoise")
##print(g2)
library(cowplot)
plot_grid(g1,g2)
```
1. "Are we comparing $Y$ values with different $Z$ values but the same $x1$ value? Does our data fitting do the same thing as actually holding constant $x1$?" (No.)
2. "Does fitting our mathematical model to data do the same thing as physically holding constant?" (No.)
3. "Do predictions of $Y$ from our model for two values of $Z$ that are 1 apart differ by the same amount regardless of (a) which two values they are and (b) any value that we put in for $x$?" (Yes. This is because we decided to describe all of the relationships with a line.)
## A 3D surface
Notice that the lines have the same slope as you move across the plane.
```{r, fig.keep="last"}
library(rgl)
n <- 20
uniq_x <- seq(0,1,length=n)
uniq_z <- seq(0,1,length=n)
region <- expand.grid(x = uniq_x, z = uniq_z)
y <- matrix((region$x + region$z), n, n)
surface3d(x=uniq_x, y=uniq_z, z=y, back = 'line', front = 'line', col = 'red', lwd = 1.5, alpha = 0.4)
axes3d()
```
## Recap summary:
- Correct interpretation of mathematical linear models may involve the word
"constant" (after all, lines have constant slope, planes have constant slopes
(one slope per dimension)).
- Mathematical linear models fit to data are not research designs. We learn
which linear model fits the data best (where "best" can be defined in least
squares ways for example), but we cannot learn whether confounding is linear
from fitting such a model.
- Linear models estimate average treatment effects well (since OLS is a
mean-difference calculator) and friendly software designers provide tests of
the weak null of no average effects by default (that are valid given
assumptions about standard errors and CLTs).
- Linear models are not research designs and should not be used as such.
- Using linear models for adjustment might make sense if you are not worried
about and/or have investigated: extrapolation, interpolation, functional
form, influential points, and you have pre-specified your specification to
avoid multiple testing problems and/or maybe generate a specification curve
(of the millions of ways to specify the **adjustment part** of the linear
model).
# How to assess the randomization process in an experiment (to teach us how to assess research designs in observational studies).
## The Neyman-Rubin Model for (simple) experiments
This is what randomization ensures:
$$ ({y_t, y_c},{X}) \perp {Z} $$
i.e., each of the distributions of $X$, $y_{c}$ and $y_{t}$ is balanced between treatment and control groups (in expectation; given variability from randomization).
- In controlled experiments, random assignment justifies this argument.
- In natural experiments, justified otherwise, this is an article of faith.
- In an experiment, the $x$es aren't necessary for inference (although
they can be used, carefully, to increase precision in both the design and
analysis phases of a project).
- **However, the part with the $x$es has testable consequences** if you worried about the success of the randomization --- say, the path between the random numbers on your computer and the application in the field.
## Covariate balance in experiments: What does it look like?
\begin{columns}
\begin{column}{.4\linewidth}
\begin{itemize}
\item \cite{arceneaux:2005}
\item Kansas City, November 2003
\item Completely randomized design: 14 precincts $\rightarrow$ Tx; 14 $\rightarrow $ Control.
\item Substantively large baseline differences (red dots)
\item<2-> Differences not large compared to other possible assignments from same design; compared to other possible experiments with the same design.
\item<2-> $\PP(\chi^{2} > x) = .91$ \citep{hansenbowers2008}. (grey lines)
\end{itemize}
\end{column}
\begin{column}{.6\linewidth}
\only<1>{\igrphx{KC-baseline}}
\only<2>{\igrphx{KC-bal+SDs}}
\end{column}
\end{columns}
## How did we do this?
```{r xb1, echo=TRUE}
acorn <- read.csv("data/acorn03.csv", row.names = 1)
xb1 <- balanceTest(z ~ v_p2003 + v_m2003 + v_g2002 + v_p2002 + v_m2002 + v_s2001 +
v_g2000 + v_p2000 + v_m2000 + v_s1999 + v_m1999 + v_g1998 +
v_m1998 + v_s1998 + v_m1997 + v_s1997 + v_g1996 + v_p1996 +
v_m1996 + v_s1996 + size, p.adjust.method = "none",
data = acorn
)
xb1$results
```
## How did we do this?
```{r xb1overall, echo=TRUE}
xb1$overall
```
```{r, out.width=".7\\textwidth", warning=FALSE}
balplot0 <- plot(xb1,statistic="adj.diff",xlab="Differences in Proportion")
balplot0_dat <- balplot0$data
xb1_df <- as_tibble(xb1$results)
names(xb1_df) <- dimnames(xb1$results)$stat
xb1_df$rowname <- dimnames(xb1$results)$vars
balplot_dat <- left_join(balplot0_dat,xb1_df,by="rowname")
balplot1 <- ggplot(data=balplot_dat,aes(x=adj.diff*100,y=rowname)) +
geom_point()+
geom_linerange(aes(xmin=-pooled.sd*100,xmax=pooled.sd*100)) +
xlim(c(-.1,.1)*100) +
theme(legend.position = "none")
print(balplot1)
```
## DeMystifying balanceTest
```{r d1, echo=TRUE}
d_stat <- function(zz, mm, ss) {
## this is the d_statistic (harmonic mean weighted diff of means statistic)
## from Hansen and Bowers 2008 almost directly from balanceTest.Engine
h.fn <- function(n, m) {
(m * (n - m)) / n
}
myssn <- apply(mm, 2, function(x) {
sum((zz - unsplit(tapply(zz, ss, mean), ss)) * x)
})
hs <- tapply(zz, ss, function(z) {
h.fn(m = sum(z), n = length(z))
})
mywtsum <- sum(hs)
myadjdiff <- myssn / mywtsum
return(myadjdiff)
}
```
## DeMystifying balanceTest
Recall our discussion of estimation "holding constant" within strata?
```{r d1v2, echo=TRUE}
## This is another version that might be more clear in regards what is going on.
d_stat_v2 <- function(zz, mm, ss) {
## mm is a data.frame
dat <- cbind(mm, z = zz, s = ss)
datb <- dat %>%
group_by(s) %>%
summarize(across(.cols = all_of(names(mm)), function(x) {
mean(x[z == 1]) - mean(x[z == 0])
}),
nb = n(),
pib = mean(z),
nbwt = nb / nrow(dat),
hbwt0 = pib * (1 - pib) * nbwt
)
datb$hbwt <- datb$hbwt0 / sum(datb$hbwt0)
# datb[,15:27]
adjmns <- datb %>% summarize(across(.cols = all_of(names(mm)), function(x) {
sum(x * hbwt)
}))
adjmnsmat <- as.matrix(adjmns)
return(adjmnsmat)
}
```
## DeMystifying balanceTest
```{r nullddistsetup, echo=TRUE}
acorncovs <- c("v_p2003", "v_m2003", "v_g2002", "v_p2002", "v_m2002", "v_s2001", "v_g2000", "v_p2000", "v_m2000", "v_s1999", "v_m1999", "v_g1998", "v_m1998", "v_s1998", "v_m1997", "v_s1997", "v_g1996", "v_p1996", "v_m1996", "v_s1996", "size")
dstats1 <- d_stat(zz = acorn$z, mm = acorn[, acorncovs], ss = rep(1, nrow(acorn)))
dstats2 <- d_stat_v2(zz = acorn$z, mm = acorn[, acorncovs], ss = rep(1, nrow(acorn)))
dstats1[1:5]
dstats2[1:5]
xb1$results[,"adj.diff",]
stopifnot(all.equal(dstats1, dstats2[1, ]))
```
```{r, eval=FALSE,echo=FALSE,results=FALSE}
## Curious whether one function is faster than the other
library(microbenchmark)
microbenchmark(d_stat(zz = acorn$z, mm = acorn[, acorncovs], ss = rep(1, nrow(acorn))),
d_stat_v2(zz = acorn$z, mm = acorn[, acorncovs], ss = rep(1, nrow(acorn))),
times = 100
)
```
## The reference distribution of the $d^2$ stat
For all vectors $z \in \Omega$ get `adj.diffs`. This is the distribution of the $d$ statistic for one-by-one balance assessment. Next question is about the distribution of the $d^2$ statistic: does it follow a $\chi^2$ distribution in this case?
```{r nulldist, cache=TRUE}
d_dist <- replicate(10000, d_stat(sample(acorn$z), acorn[, acorncovs], ss = rep(1, nrow(acorn))))
```
Get the randomization-based $p$-values:
```{r echo=TRUE}
xb1ds <- xb1$results[, "adj.diff", ]
xb1ps <- xb1$results[, "p", ]
obs.d <- d_stat(acorn$z, acorn[, acorncovs], rep(1, nrow(acorn)))
dps <- matrix(NA, nrow = length(obs.d), ncol = 1)
for (i in 1:length(obs.d)) {
dps[i, ] <- 2 * min(mean(d_dist[i, ] >= obs.d[i]), mean(d_dist[i, ] <= obs.d[i]))
}
## You can compare this to the results from balanceTest
round(cbind(randinfps = dps[, 1], xbps = xb1ps, obsdstats = obs.d, xbdstats = xb1ds), 3)
```
## Reference distribution of the $d^2$ stat {.allowframebreaks}
The $d^2$ statistic is a linear function of the probably correlated $d$-statistics: a linear combination of correlated variables is $d^{T} \Sigma_d^{-1} d$ where $d$ is a vector of the stratum adjusted differences in means and $\Sigma_d$ is the variance-covariance matrix of the distribution of the $d$ statistics under the sharp null of no differences. With only one variable, this is basically a standardized $d$ statistic (after taking sqrt, and forced to be positive).
```{r d2stat, echo=TRUE}
d2_stat <- function(dstats, ddist = NULL, theinvcov = NULL) {
## d is the vector of d statistics
## ddist is the matrix of the null reference distributions of the d statistics
if (is.null(theinvcov) & !is.null(ddist)) {
as.numeric(t(dstats) %*% solve(cov(t(ddist))) %*% dstats)
} else {
as.numeric(t(dstats) %*% theinvcov %*% dstats)
}
}
```
## Reference distribution of the $d^2$ stat
The distribution of the $d^2$ statistic arises from the distribution of the d statistics --- for each draw from the set of treatment assignments we can collapse the $d$-statistics into one $d^2$. And so we can calculate the $p$-value for the $d^2$.
```{r d22, echo=TRUE}
## Here we have the inverse of the covariance/variance matrix of the d statistics
invCovDDist <- solve(cov(t(d_dist)))
obs.d2 <- d2_stat(obs.d, d_dist, invCovDDist)
d2_dist <- apply(d_dist, 2, function(thed) {
d2_stat(thed, theinvcov = invCovDDist)
})
## The chi-squared reference distribution only uses a one-sided p-value going in the positive direction
d2p <- mean(d2_dist >= obs.d2)
cbind(obs.d2, d2p)
xb1$overall
```
```{r, eval=FALSE, echo=FALSE, results=FALSE, out.width=".7\\textwidth"}
plot(density(d2_dist))
rug(d2_dist)
abline(v = obs.d2)
```
## Why differences between balanceTest and d2?
I suspect that $N=28$ is too small. `balanceTest` uses an asymptotic
approximation to the randomization distribution.
```{r echo=FALSE, out.width=".8\\textwidth", cache=FALSE}
par(mfrow = c(1, 2),pty="m",oma=rep(0,4),mgp=c(1.5,.5,0),mar=c(3,3,0,0))
qqplot(rchisq(10000, df = 21), d2_dist)
abline(0, 1)
plot(density(d2_dist),main="",xlim=c(2,60))
rug(d2_dist)
lines(density(rchisq(10000, df = 21)),col="grey")
abline(v=c(obs.d2,xb1$overall$chisquare),col=c("black","grey"))
```
## Summary
- Randomization balances covariate distributions between treated and control groups.
- We can use randomization inference to check the randomization procedure (mostly useful if there is a long chain of communication between the random number generator and the field).
- **Randomization does not imply exact equivalence. Large differences in covariates easily arise in small experiments.**
# Assessing comparisons in observational studies
```{r cache=TRUE}
load(url("http://jakebowers.org/Data/meddat.rda"))
```
## Introducing the Medellin Data
Cerdá et al. collected data on about roughly `r nrow(meddat)`
neighborhoods in Medellin, Colombia. About `r signif(sum(meddat$nhTrt),2)` had
access to the new Metrocable line and `r signif(sum(1-meddat$nhTrt),2)` did not.
\centering
\includegraphics[width=.7\textwidth]{medellin-gondola.jpg}
<!-- For more on the Metrocable project see <https://www.medellincolombia.co/where-to-stay-in-medellin/medellin-orientation/> and <https://archleague.org/article/connective-spaces-and-social-capital-in-medellin-by-jeff-geisinger/> -->
## Introducing the Medellin Data
Cerdá et al. collected data on about roughly `r nrow(meddat)`
neighborhoods in Medellin, Colombia. About `r signif(sum(meddat$nhTrt),2)` had
access to the new Metrocable line and `r signif(sum(1-meddat$nhTrt),2)` did not.
\centering
\includegraphics[width=.8\textwidth]{medellin-conc-pov.jpg}
## Introducing the Medellin Data: Variables Collected
\scriptsize
```
## The Intervention
nhTrt Intervention neighborhood (0=no Metrocable station, 1=Metrocable station)
## Some Covariates (there are others, see the paper itself)
nh03 Neighborhood id
nhGroup Treatment (T) or Control (C)
nhTrt Treatment (1) or Control (0)
nhHom Mean homicide rate per 100,000 population in 2003
nhDistCenter Distance to city center (km)
nhLogHom Log Homicide (i.e. log(nhHom))
## Outcomes (BE03,CE03,PV03,QP03,TP03 are baseline versions)
BE Neighborhood amenities Score 2008
CE Collective Efficacy Score 2008
PV Perceived Violence Score 2008
QP Trust in local agencies Score 2008
TP Reliance on police Score 2008
hom Homicide rate per 100,000 population Score 2008-2003 (in log odds)
HomCount2003 Number of homicides in 2003
Pop2003 Population in 2003
HomCount2008 Number of homicides in 2008
Pop2008 Population in 2008
```
Get rates from counts:
```{r rates, echo=TRUE}
meddat <- mutate(meddat,
HomRate03 = (HomCount2003 / Pop2003) * 1000,
HomRate08 = (HomCount2008 / Pop2008) * 1000
)
```
## What is the effect of the Metrocable on Homicides? {.allowframebreaks}
One approach: Estimate the average treatment effect of Metrocable on
Homicides after the stations were built.
```{r lmone, echo=TRUE}
## code here
themeans <- group_by(meddat, nhTrt) %>% summarise(ybar = mean(HomRate08))
diff(themeans$ybar)
lmOne <- lm(HomRate08 ~ nhTrt, meddat)
coef(lmOne)["nhTrt"]
library(estimatr)
difference_in_means(HomRate08 ~ nhTrt, meddat)
```
Another approach, test the null of no effects:
```{r initialtest, echo=TRUE}
balanceTest(nhTrt ~ HomRate08, data = meddat)
meddat$nhTrtF <- factor(meddat$nhTrt)
test2 <- oneway_test(HomRate08 ~ nhTrtF, data = meddat, distribution = asymptotic())
test3 <- oneway_test(HomRate08 ~ nhTrtF, data = meddat, distribution = approximate(nresample = 1000))
test4 <- wilcox_test(HomRate08 ~ nhTrtF, data = meddat, distribution = approximate(nresample = 1000))
pvalue(test2)
pvalue(test3)
pvalue(test4)
```
## Do we have any concerns about confounding?
Sometimes people ask about "bias from observed confounding" or "bias from selection on observables".
How would we interpret the following results where `nhAboveHS` is proportion
with more than a high school education in the neighborhood in 2003 or so and
`nhTrt` is 0=no station built, 1=station built? (Recall how we justified the
use of `balanceTest` in terms of randomization above.)
```{r xbmed, echo=TRUE}
xbMed1 <- balanceTest(nhTrt ~ nhAboveHS, data = meddat)
xbMed1$overall
xbMed1$results
```
## How would you adjust for Proportion Above HS Degree?
Part of the Metrocable effect is not about Metrocable per se, but rather about
the education of people in the neighborhood. How should we remove `nhAboveHS`
from our estimate or test? What strategies can you think of?
## One approach to this problem: model-based adjustment
Let's try to just adjust for this covariate in a very common manner:
```{r echo=FALSE}
lm1 <- lm(HomRate08 ~ nhTrt + nhAboveHS, data = meddat)
```
```{r echo=FALSE}
preddat <- expand.grid(nhTrt = c(0, 1), nhAboveHS = range(meddat$nhAboveHS))
preddat$fit <- predict(lm1, newdata = preddat)
```
\centering
```{r, out.width=".9\\textwidth", echo=FALSE}
par(oma = rep(0, 4), mgp = c(1.5, .5, 0), mar = c(3, 3, 0, 0))
with(meddat, plot(nhAboveHS, HomRate08, pch = c(1, 2)[nhTrt + 1]))
with(subset(preddat, subset = nhTrt == 0), lines(nhAboveHS, fit, lty = 1))
with(subset(preddat, subset = nhTrt == 1), lines(nhAboveHS, fit, lty = 2))
## locator()
text(c(0.111807, 0.001629), c(1.871, 2.204), labels = c("Treat", "Control"), pos = 1)
text(c(.3, .5), c(coef(lm1)[1] + coef(lm1)[3] * .3, coef(lm1)[1] + coef(lm1)[2] + coef(lm1)[3] * .5),
labels = c("Control", "Treat")
)
```
## Exactly what does this kind of adjustment do?
Notice that I can get the same coefficient (the effect of Metrocable on
Homicides adjusted for HS-Education in the neighborhood) either directly (as
earlier) or via **residualization**:
```{r echo=TRUE}
coef(lm1)["nhTrt"]
eYX <- residuals(lm(HomRate08 ~ nhAboveHS, data = meddat))
eZX <- residuals(lm(nhTrt ~ nhAboveHS, data = meddat))
lm1a <- lm(eYX ~ eZX)
coef(lm1a)[2]
```
## Exactly what does this kind of adjustment do?
So, how would you explain what it means to "control for HS-Education" here?
```{r}
plot(eZX, eYX)
```
## Did we adjust enough?
Maybe adding some more information to the plot can help us decide whether, and to what extend, we effectively "controlled for" the proportion of the neighborhood with more than High School education. Specifically, we might be interested in assessing extrapolation/interpolation problems arising from our linear assumptions.
\centering
```{r, out.width=".6\\textwidth", echo=FALSE, warning=FALSE, message=FALSE}
par(oma = rep(0, 4), mgp = c(1.5, .5, 0), mar = c(3, 3, 0, 0))
with(meddat, plot(nhAboveHS, HomRate08, pch = c(1, 2)[nhTrt + 1]))
with(subset(preddat, subset = nhTrt == 0), lines(nhAboveHS, fit, lty = 1))
with(subset(preddat, subset = nhTrt == 1), lines(nhAboveHS, fit, lty = 2))
with(subset(meddat, subset = nhTrt == 0), lines(loess.smooth(nhAboveHS, HomRate08, deg = 1, span = 2 / 3), lty = 1))
with(subset(meddat, subset = nhTrt == 1), lines(loess.smooth(nhAboveHS, HomRate08, deg = 1, span = .8), lty = 2))
## locator()
text(c(0.111807, 0.001629), c(1.871, 2.204), labels = c("Treat", "Control"), pos = 1)
text(c(.3, .5), c(coef(lm1)[1] + coef(lm1)[3] * .3, coef(lm1)[1] + coef(lm1)[2] + coef(lm1)[3] * .5),
labels = c("Control", "Treat")
)
with(subset(meddat, subset = nhTrt == 0), rug(nhAboveHS))
with(subset(meddat, subset = nhTrt == 1), rug(nhAboveHS, line = -.5))
```
How should we interpret this adjustment? How should we judge the improvement that we made? What concerns might we have?
```{r echo=FALSE, eval=FALSE}
thecovs <- unique(c(names(meddat)[c(5:7, 9:24)], "HomRate03"))
balfmla <- reformulate(thecovs, response = "nhTrt")
xbMed <- balanceTest(balfmla,
data = meddat,
p.adjust.method = "none"
)
xbMed$overall
xbMed$results["nhAboveHS", , ]
```
```{r echo=FALSE, eval=FALSE}
outcomefmla <- reformulate(c("nhTrt", thecovs), response = "HomRate08")
lmbig <- lm(outcomefmla, data = meddat)
```
## How would you adjust for Proportion Above HS Degree?
So, part of the Metrocable effect might not reflect the causal effect of
Metrocable per se, but rather the education of people in the
neighborhood. How should we remove `nhAboveHS` from our estimate or test? What
strategies can you think of?
Features of a good adjustment process:
- Blind to outcome analysis (to preserve false positive rate and deter critics). Able to be pre-registered. Perhaps even reviewed by stakeholders.
- Easy to interpret ("controlling for" versus "holding constant")
- Easy to diagnoses (Easy to answere the question "Did we adjust enough?")
## Stratification V 1.0
```{r strat1, echo=TRUE}
lm1a <- lm(HomRate08 ~ nhTrt, data = meddat, subset = nhAboveHS >= .1)
lm1b <- lm(HomRate08 ~ nhTrt, data = meddat, subset = nhAboveHS < .1)
res_strat <- c(hiEd_Effect = coef(lm1a)["nhTrt"], loEd_Effect = coef(lm1b)["nhTrt"])
res_strat
n_strat <- table(meddat$nhAboveHS >= .1)
n_strat
stopifnot(sum(n_strat) == nrow(meddat)) ## A test of code
sum(res_strat * rev(n_strat) / 45) ## What is happening here?
## Putting this together
outcome_analysis_strat <- meddat %>% group_by(nhAboveHS>=.1) %>%
summarize(nb=n(),nT=sum(nhTrt),nC=nb-nT,pr_trt=mean(nhTrt),bar_y_t=mean(HomRate08[nhTrt==1]),
bar_y_c=mean(HomRate08[nhTrt==0]),ate_b=bar_y_t - bar_y_c)
outcome_analysis_strat <- outcome_analysis_strat %>% mutate(nbwt=nb/sum(nb),
prec_wt0 = nbwt * pr_trt * (1-pr_trt))
outcome_analysis_strat$prec_wt <-
with(outcome_analysis_strat,prec_wt0/sum(prec_wt0))
outcome_analysis_strat
outcome_analysis_strat %>% summarize(ate_block_size= sum(ate_b * nbwt),
ate_prec_wt = sum(ate_b * prec_wt/sum(prec_wt)))
```
*But, standard errors? p-values? confidence intervals?*
## Stratified adjustment V 2.0
One-step stratified estimation.
```{r strat2, echo=TRUE}
## Weight by block size
ate1c <- difference_in_means(HomRate08 ~ nhTrt, blocks = I(nhAboveHS >= .1), data = meddat)
ate1c
## Weight by both block size and proportion in treatment vs control ("harmonic weight")
lm1c <- lm_robust(HomRate08 ~ nhTrt, fixed_effects = ~ I(nhAboveHS >= .1), data = meddat)
coef(lm1c)["nhTrt"]
lm1d <- lm(HomRate08 ~ nhTrt + I(nhAboveHS >= .1), data = meddat)
coef(lm1d)["nhTrt"]
```
## Stratified adjustment V 2.0 {.allowframebreaks}
One-step stratified testing
```{r echo=TRUE}
xbate1 <- balanceTest(nhTrt ~ HomRate08+ strata(I(nhAboveHS >= .1)), data = meddat)
xbate1$results[, c("adj.diff","p"), ]
xbate1$overall
## Effect of the treatment on the treated weights
outcome_analysis_strat$nTwt <- with(outcome_analysis_strat,nT/sum(nT))
with(outcome_analysis_strat,sum(ate_b*nTwt))
## Approximating the as-if-randomized null distribution with a Normal
## approximation
hstest2 <- independence_test(HomRate08~nhTrt|factor(nhAboveHS >= .1),data=meddat)
## Now using the "as-if-randomized" distribution directly
set.seed(12345)
hstest2_perm <- independence_test(HomRate08~nhTrt|factor(nhAboveHS >= .1),data=meddat,distribution=approximate(nresample=10000))
pvalue(hstest2)
pvalue(hstest2_perm)
## Now trying different test statistics
hstest4 <- independence_test(HomRate08~nhTrt|factor(nhAboveHS >= .1),data=meddat,ytrafo=rank_trafo)
pvalue(hstest4)
hstest5 <- wilcox_test(HomRate08~factor(nhTrt)|factor(nhAboveHS >= .1),data=meddat)
pvalue(hstest5)
```
## Balance assessment after stratification
Did we adjust enough? What would *enough* mean? Use the testing approach but now focus only on the covariate(s) that you are trying to adjust.
```{r xbHS1, echo=TRUE}
xbHS1 <- balanceTest(nhTrt ~ nhAboveHS+strata(I(nhAboveHS >= .1)), data = meddat)
xbHS1$overall
xbHS1$results[1, c("Treatment", "Control", "adj.diff", "std.diff", "z", "p"), ] ## the covariate specific z-test
```
## Disadvantages and Advantages of Simple Stratification
- (+) Easy to explain what "controlling for" or "adjustment" means.
- (-) Hard to justify any particular cut-point
- (-) We could probably adjust *more* --- comparing neighborhoods similar in education rather than just within big strata
## The Curse of Dimensionality and linear adjustment for one more variable.
What about more than one variable? Have we controlled for both population
density and educational attainment enough? How would we know?
```{r lm2x, echo=TRUE}
lm2x <- lm(HomRate08 ~ nhTrt + nhPopD + nhAboveHS, data = meddat)
coef(lm2x)["nhTrt"]
```
Maybe another plot?
```{r eval=FALSE}
meddat$nhTrtF <- factor(meddat$nhTrt)
library(car)
scatter3d(HomRate08 ~ nhAboveHS + nhPopD,
groups = meddat$nhTrtF,
data = meddat, surface = TRUE,
fit = c("linear")
) # additive"))
```
```{r echo=FALSE, eval=FALSE}
scatter3d(HomRate08 ~ nhAboveHS + nhPopD,
groups = meddat$nhTrtF,
data = meddat, surface = TRUE,
fit = c("additive")
)
```
## The Problem of Using the Linear Model for Adjustment
- Problem of Interepretability: "Controlling for" is "removing (additive) linear relationships" it is not "holding constant"
- Problem of Diagnosis and Assessment: What is the standard against which we can compare a given linear covariance adjustment specification?
- Problem of extrapolation and interpolation: Often known as "common support", too.
- Problems of overly influential points and curse of dimensionality: As dimensions increase, odds of influential point increase (ex. bell curve in one dimension, one very influential point in 2 dimensions); also real limits on number of covariates (roughly $\sqrt{n}$ for OLS).
## The Problem of Using the Linear Model for Adjustment
- Problems of bias even in randomized experiments:
\begin{equation}
Y_i = \beta_0 + \beta_1 Z_i + e_i
\label{eq:olsbiv}
\end{equation}
This is a common practice because, we know that the formula to estimate
$\beta_1$ in equation \eqref{eq:olsbiv} is the same as the difference of means
in $Y$ between treatment and control groups:
\begin{equation}
\hat{\beta}_1 = \overline{Y|Z=1} - \overline{Y|Z=0} = \frac{cov(Y,Z)}{var(Z)}.
\end{equation}
\begin{equation}
Y_i = \beta_0 + \beta_1 Z_i + \beta_2 X_i + e_i \label{eq:olscov}
\end{equation}
What is $\beta_1$ in this case? We know the matrix representation here $(\bX^{T}\bX)^{-1}\bX^{T}\by$, but here is the scalar formula for this particular case in \eqref{eq:olscov}:
\begin{equation}
\hat{\beta}_1 = \frac{\var(X)\cov(Z,Y) - \cov(X,Z)\cov(X,Y)}{\var(Z)\var(X) - \cov(Z,X)^2}
\end{equation}
## Can we improve stratified adjustment?
Rather than two strata, why not three?
```{r lm1cut3, echo=TRUE}
lm1cut3 <- lm(HomRate08 ~ nhTrt + cut(nhAboveHS, 3), data = meddat)
coef(lm1cut3)["nhTrt"]
```
But why those cuts? And why not 4? Why not...?
**One idea:** collect observations into strata such that the sum of the
differences in means of `nhAboveHS` within strata is smallest? This is the idea
behind `optmatch` and other matching approaches.
## The optmatch workflow: The distance matrix
Introduction to `optmatch` workflow. To minimize differences requires a matrix
of those differences (in general terms, a matrix of distances between the
treated and control units)
```{r optm1, echo=TRUE}
tmp <- meddat$nhAboveHS
names(tmp) <- rownames(meddat)
absdist <- match_on(tmp, z = meddat$nhTrt, data = meddat)
absdist[1:3, 1:3]
abs(meddat$nhAboveHS[meddat$nhTrt == 1][1] - meddat$nhAboveHS[meddat$nhTrt == 0][1])
```
## Created a Stratified Research Design
```{r fm1, echo=TRUE}
fm1 <- fullmatch(absdist, data = meddat)
summary(fm1, min.controls = 0, max.controls = Inf)
table(meddat$nhTrt, fm1)
pm1 <- pairmatch(absdist, data = meddat)
summary(pm1, min.controls = 0, max.controls = Inf)
table(meddat$nhTrt, pm1, exclude = c())
```
## Evaluate the design: Within set differences
```{r echo=FALSE}
meddat$fm1 <- fm1
meddat$pm1 <- pm1
```
Differences within sets versus raw differences from the fullmatch.
```{r echo=FALSE, out.width=".9\\textwidth"}
library(gridExtra)
bpfm1 <- ggplot(meddat, aes(x = fm1, y = nhAboveHS)) +
geom_boxplot() +
stat_summary(fun = mean, geom = "point", shape = 20, size = 3, color = "red", fill = "red")
meddat$nostrata <- rep(1, 45)
bporig <- ggplot(meddat, aes(x = nostrata, y = nhAboveHS)) +
geom_boxplot() +
stat_summary(
fun = mean, geom = "point",
shape = 20, size = 3, color = "red", fill = "red"
)
grid.arrange(bpfm1, bporig, ncol = 2, layout_matrix = matrix(c(1, 1, 1, 1, 2), nrow = 1))
```
## Evaluate the design: Within set differences
Differences within sets versus raw differences from the pairmatch.
```{r echo=FALSE, out.width=".9\\textwidth"}
bppm1 <- ggplot(meddat, aes(x = pm1, y = nhAboveHS)) +
geom_boxplot() +
stat_summary(fun = mean, geom = "point", shape = 20, size = 3, color = "red", fill = "red")
grid.arrange(bppm1, bporig, ncol = 2, layout_matrix = matrix(c(1, 1, 1, 1, 2), nrow = 1))
```
## Evaluate the design: Inspect within set differences
```{r sdiffs, echo=FALSE}
rawmndiffs <- with(meddat, mean(nhAboveHS[nhTrt == 1]) - mean(nhAboveHS[nhTrt == 0]))
setdiffsfm1 <- meddat %>%
group_by(fm1) %>%
summarize(
mneddiffs =
mean(nhAboveHS[nhTrt == 1]) -
mean(nhAboveHS[nhTrt == 0]),
mnAboveHS = mean(nhAboveHS),
minAboveHS = min(nhAboveHS),
maxAboveHS = max(nhAboveHS)
)
setdiffsfm1
# summary(setdiffs$mneddiffs)
# quantile(setdiffs$mneddiffs, seq(0,1,.1))
```
## Evaluate the design: Inspect within set differences
```{r echo=FALSE, warnings=FALSE}
setdiffspm1 <- meddat %>%
group_by(pm1) %>%
summarize(
mneddiffs =
mean(nhAboveHS[nhTrt == 1]) -
mean(nhAboveHS[nhTrt == 0]),
mnAboveHS = mean(nhAboveHS),
minAboveHS = min(nhAboveHS),
maxAboveHS = max(nhAboveHS)
)
setdiffspm1
```
## Evaluate the design: Compare to a randomized experiment.
The within-set differences look different from those that would be expected
from a randomized experiment.
```{r xbhs2, echo=TRUE}
xbfm1 <- balanceTest(nhTrt ~ nhAboveHS+strata(fm1), data = meddat)
xbfm1$results
xbfm1$overall
```
## What is balanceTest doing?
```{r xbagain, echo=TRUE}
setmeanDiffs <- meddat %>%
group_by(fm1) %>%
summarise(
diffAboveHS = mean(nhAboveHS[nhTrt == 1]) - mean(nhAboveHS[nhTrt == 0]),
nb = n(),
nTb = sum(nhTrt),
nCb = sum(1 - nhTrt),
hwt = (2 * (nCb * nTb) / (nTb + nCb))
)
setmeanDiffs
```
## What is balanceTest doing with multiple sets/blocks?
The test statistic is a weighted average of the set-specific differences (same
approach as we would use to test the null in a block-randomized experiment)