-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path03-mrp_ideal.Rmd
2401 lines (2079 loc) · 134 KB
/
03-mrp_ideal.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
# Ideal Point MRP
```{r, include=FALSE}
library(data.table)
library(dplyr)
library(forcats)
library(tidyr)
library(reshape2)
library(stringr)
library(ggplot2)
library(rstan)
library(rstanarm)
library(usmap)
library(gridExtra)
library(scales)
library(kableExtra)
library(readr)
#Sys.setenv(LOCAL_CPPFLAGS = '-march=corei7 -mtune=corei7')
options(mc.cores = parallel::detectCores(logical = FALSE))
```
This chapter introduces ideal point MRP, an alternative to standard MRP that can be used when a survey contains at least two related questions that reflect the same attitude or ability. We will present how this method can be used for obtaining sub-national estimates of the latent attitude and also for improving estimates with respect to the individual questions.
## Introduction and Literature
### The ABC of IRT
Being developed in educational research, ideal point models (also called Item Response Theory models) assume that each participant $j$ has a latent ability $\alpha_j$. In the context of a math exam, this ability parameter reflects how good a certain student is at math. Of course, $\alpha_j$ is said to be latent because we do not observe it directly, but only through the student's answers to $k$ math-related questions. The ideal point model maps the unobserved ability $\alpha_j$ to the probability that subject $j$ answers correctly question $k$:
$$
P(y = 1) = logit^{-1}(\alpha_j - \beta_k)
$$
The probability of correctly answering question $k$ does not only depend on the student's ability $\alpha_j$, but also on the question difficulty $\beta_k$. Let's imagine a student with $\alpha_1 = 2$ that answers two questions with difficulties $\beta_1 = 0$ and $\beta_2 = 3$. In the case of her responding to the first question, we have that there is a $logit^{-1}(2 - 0) = 88\%$ probability of answering it correctly. In the case of the second question she has a lower probability of getting it right: $logit^{-1}(2 - 3) = 27\%$. This is because the second question is much more difficult than the first. If we now take a second student with a lower ability $\alpha_2 = -1.5$, his probabilities of getting these questions correctly are $logit^{-1}(-1.5 - 0) = 18\%$ and $logit^{-1}(-1.5 - 3) = 1\%$.
In some situations not every individual encounters every question. In this case, the ideal point model can be written as $P(y_i = 1) = logit^{-1}(\alpha_{j[i]} - \beta_{k[i]})$. In this case, the index $i$ corresponds to the question $k[i]$ responded by the student $j[i]$. Although we will use this notation, in the data we will use for this case study all individuals have responded to all of the questions considered.
The above model, which is usually referred as Rasch model or one-parameter model, assumes each question is equally relevant (or discriminatory) in terms of measuring the latent ability $\alpha_j$. Although in educational testing it is desirable to construct questions that are able to discriminate between a student with a low ability and another one with high ability, in practice not all items achieve this to the same extent. This is exactly what the discrimination parameter $\gamma_k$ reflects. Thus, this extended version that is often called two-parameter ideal point model becomes:
$$
P(y_i = 1) = \gamma_{k[i]} (logit^{-1}(\alpha_{j[i]} - \beta_{k[i]}))
$$
Let's consider two questions with equal difficulty $\beta_1 = 0$ and $\beta_2 = 0$, but with different discrimination $\gamma_1 = 0.1$ and $\gamma_2 = 2.5$. The high-ability student described previously has a $logit^{-1}(0.1 \times (2 - 0) = 55\%$ probability of responding correctly to the first question, while the low-ability participant has a $logit^{-1}(0.1 \times (-1.5 - 0) = 46\%$ chance. These probabilities are close because this question has a low discrimination parameter, and is therefore not particularly good at distinguishing between high-ability and low-ability individuals. Conversely, the second question has a high discrimination parameter, and therefore the probabilities for these two students are $logit^{-1}(1.7 \times (2 - 0) = 97\%$ and $logit^{-1}(1.7 \times (-1.5 - 0) = 7\%$, respectively.
It is sometimes useful to think about the ideal point model as a function that transforms a latent ability $\alpha_j$ into the probably of answering correctly a certain question. This mapping depends on the characteristics of the question, which in the case of the two-parameter ideal point model are the difficulty $\beta_k$ and the discrimination $\gamma_k$. We can visualize how different values for $\beta_k$ and $\gamma_k$ influence this transformation.
```{r, fig.height= 6, fig.width=14, echo=FALSE, fig.align = "center", warning=FALSE, message=FALSE}
plot_prob <- function(gamma = 1, beta = 0, sequence = seq(-5, 5, by = 0.01)){
ggplot(data=data.frame(seq = sequence)) +
geom_hline(aes(yintercept = 0)) +
geom_line(aes(x=seq, y=plogis(gamma*(seq - beta)))) +
scale_y_continuous(limits = c(0, 1),
expand=c(0,0)) +
theme_bw() +
labs(x="",y="")+
theme(legend.position="none",
axis.title=element_text(size=10),
axis.text.y=element_text(size=10),
axis.text.x=element_text(size=5, vjust=0.3),
legend.title=element_text(size=10),
legend.text=element_text(size=10)) +
ggtitle(latex2exp::TeX(paste0("$\\gamma_k = $", gamma, "\t", "$\\beta_k = $", beta))) +
xlab(latex2exp::TeX("$\\alpha_j$"))
}
grid.arrange(plot_prob(gamma = 0.5, beta = 1), plot_prob(gamma = 1, beta = 1), plot_prob(gamma = 2, beta = 1),
plot_prob(gamma = 0.5, beta = 0), plot_prob(gamma = 1, beta = 0), plot_prob(gamma = 2, beta = 0),
plot_prob(gamma = 0.5, beta = -1), plot_prob(gamma = 1, beta = -1), plot_prob(gamma = 2, beta = -1),
nrow = 3, ncol = 3)
```
#### Multilevel structure and identification
The parameters used in the ideal point model are often assumed to follow a multilevel structure that assigns normal distributions to the abilities, difficulties, and discriminations:
$$
\begin{align}
\alpha_j &\sim \text{normal}(\mu_{\alpha}, \sigma_{\sigma}) \text{ for } j = 1, ..., J \\
\beta_k &\sim \text{normal}(\mu_{\beta}, \sigma_{\beta}) \text{ for } k = 1, ..., K \\
\gamma_k &\sim \text{normal}(\mu_{\gamma}, \sigma_{\gamma}) \text{ for } k = 1, ..., K \\
\end{align}
$$
However, the two-parameter ideal point model is not identified. In particular, it suffers from three problems (see @bafumi2005practical for a more detailed discussion on identification problems and solutions):
1. Additive aliasing: Adding a constant to $\alpha_j$ and $\beta_k$ will not change its predictions.
2. Multiplicative aliasing: Similarly, multiplying $\gamma_k$ by a constant and dividing $(\alpha_j - \beta_j)$ by the same constant will keep the predictions unchanged.
3. Reflection invariance: Lastly, multiplying the ability, difficulty, and discrimination parameter by -1 will also result in identical predictions.
The first two issues can be resolved by creating standardized parameters $\alpha_j^{\rm adj} = \frac{\alpha_j - \bar{\alpha}}{s_{\alpha}}$, $\beta_k^{\rm adj} = \frac{\beta_k - \bar{\alpha}}{s_{\alpha}}$, and $\gamma_k^{\rm adj} = \gamma_k s_{\alpha}$. The new ability, difficulty, and discrimination parameters are well defined and preserve the likelihood as $P(y_i = 1) = logit^{-1}(\gamma_{k[i]}(\alpha_{j[i]} - \beta_{k[i]})) = logit^{-1}(\gamma_{k[i]}^{\rm adj}(\alpha_{j[i]}^{\rm adj} - \beta_{k[i]}^{\rm adj}))$. Reflection invariance can be avoided by restricting $\gamma_k \gt 0$ (and consequently $\mu_{\gamma} \gt 0$ and also $\gamma_k^{adj} \gt 0$), which in turn requires precoding the questions so they are in the same direction (e.g. indicating conservative positions).
#### Including predictors for $\alpha_j$
The mode we have described assumes that the abilities $\alpha_j$ follow a normal distribution centered at the population average ability $\mu_{\alpha}$ with a standard deviation $\sigma_{\sigma}$. We can extend this by adding ability-level predictors, resulting in $\alpha_j \sim \text{normal}(\mu_{\alpha} + X \beta)$ where $\mu_{\alpha}$ now represents the regression intercept.
### Ideal point models and estimating public opinion
Until now we have used the example of a math test. However, beyond educational settings an ideal point model can be used to reflect other situations in which a latent characteristic determines a dichotomous response. In the Political Science literature, these models have been famously used to reflect the ideological position of legislators based on their roll call voting records (@clinton2004statistical). Similarly, we can use the survey respondents support for different statements as reflecting a latent attitude based on a series of survey questions. There have been two main bodies of work that have combined ideal-point models and MRP.
@tausanovitch2013ideal follow a two-step process to estimate policy preferences across states and cities in the US. First, they fit a unidimensional ideal point model such as the one described by @clinton2004statistical based on dichotomous responses from the CCES and the ACS, obtaining estimates of the liberalness-conservativeness for 270,000 Americans. Instead of using dissaggregation, the second step involves using an MRP approach that instead of considering the response to any individual question as the outcome they predict this estimated ideal point for each participant. In a later work, @tausanovitch2014representation correlate the city-level policy preference estimates obtained using this method with the policies enacted at the municipal level, finding a clear correspondence.
In a related line of work, @caughey2015dynamic use a conceptually different approach in order to estimate latent abilities over time. First, they model survey responses not at the individual level, but rather at the level of subpopulation groups defined by demographic and geographic characteristics. This has the advantage of using highly sparse data without requiring ‘linking’ questions that bridge across all the surveys. Second, they extend the model to borrow information across time, which allows to create time-specific estimates of average group opinion. They use this dynamic group-level IRT framework to estimate policy liberalism at the U.S. state level in each year between 1972 and 2012 (for other applications, see @bergquist2019does and @bergquist2019does).
## A Two-Parameter IRT Model with Latent Multilevel Regression
In the previous two chapters we have only considered one of the questions in the CCES. However, this survey includes six support/oppose statements about abortion:
* CC18_321a: Always allow a woman to obtain an abortion as a matter of choice.
* CC18_321b: Permit abortion ONLY in case of rape, incest or when the woman’s life is in danger.
* CC18_321c: Ban abortions after the 20th week of pregnancy.
* CC18_321d: Allow employers to decline coverage of abortions in insurance plans.
* CC18_321e: Prohibit the expenditure of funds authorized or appropriated by federal law for any abortion.
* CC18_321f: Make abortions illegal in all circumstances.
We can use a two-parameter logistic item response model with a latent (multilevel) regression to model $k$ questions based on $j$ respondents:
$$
\begin{equation*}
P(y_i = 1) = logit^{-1}(\gamma_{k[i]}^{adj}(\alpha_{j[i]}^{adj} - \beta_{k[i]}^{adj}))
\end{equation*}
$$
where:
$$
\begin{align*}
\alpha_j &\sim {\rm normal}(\mu^{\alpha} + A_{\rm s[j]}^{\rm state}
+ A_{\rm a[j]}^{\rm age}
+ A_{\rm r[j]}^{\rm ethnicity}
+ A_{\rm e[j]}^{\rm education}
+ B^{\rm male} \cdot {\rm Male}_{\rm j}, \sigma^{\alpha}) {\rm \ for} \ j = 1,...,J \\
\beta_k &\sim {\rm normal}(\mu^{\beta}, \sigma^{\beta}) {\rm \ for} \ k = 1,...,K \\
\gamma_k &\sim {\rm normal_{+}}(\mu^{\gamma}, \sigma^{\gamma}) {\rm \ for} \ k = 1,...,K
\end{align*}
$$
and:
$$
\begin{align*}
A_{\rm s}^{\rm state} &\sim {\rm normal}(A^{\rm region}_{n[s]} + B^{\rm repvote} \cdot {\rm RepVote}_{\rm s}, \sigma^{\rm state}) \textrm{ for s = 1,...,50}\\
A_{\rm a}^{\rm age} & \sim {\rm normal}(0,\sigma^{\rm age}) \textrm{ for a = 1,...,6}\\
A_{\rm r}^{\rm ethnicity} & \sim {\rm normal}(0,\sigma^{\rm ethnicity}) \textrm{ for r = 1,...,4}\\
A_{\rm e}^{\rm education} & \sim {\rm normal}(0,\sigma^{\rm education}) \textrm{ for e = 1,...,5}\\
A_{\rm n}^{\rm region} & \sim {\rm normal}(0,\sigma^{\rm region}) \textrm{ for a = 1,...,4}\\
\end{align*}
$$
Note that our model is fundamentally different from the two-step approach used by @tausanovitch2013ideal. By first estimating the ideal point of each individual and then using MRP, their method is not propagating the uncertainty about the estimated ideal points into the final national or subnational estimates. Considering one of the essential advantages of Bayesian inference is to properly quantify uncertainty, we include the multilevel stage of the MRP within the ideal point model model. Thus, in our model the multilevel regression serves as a prior for $\alpha_j$. In this example we have included the same predictors introduced in first chapter, excluding the interaction terms for simplicity.
As we already introduced in the previous section, identification can be achieved by transforming the ability, difficulty, and discrimination parameters by $\alpha_j^{\rm adj} = \frac{\alpha_j - \bar{\alpha}}{s_{\alpha}}$, $\beta_k^{\rm adj} = \frac{\beta_k - \bar{\alpha}}{s_{\alpha}}$, $\gamma_k^{\rm adj} = \gamma_k s_{\alpha}$. We also restricted $\gamma_k > 0$, which in turn requires precoding all the questions. The first question was reversed in order for all the outcomes to reflect a supporting perspective on restricting abortion rights. Therefore, a high ability $\alpha_j^{\rm adj}$ will represent a strong opposition to abortion.
### Bayesian estimation
In this initial experiment we analyzed the six abortion responses for a random sample of 5,000 CCES participants. The Stan code we used is shown below, and was fitted using 5 chains with 2,000 iterations (1,000 warmup).
```{r, echo = FALSE, include = FALSE}
clean_cces <- function(df, list_states_abb, list_states_num){
## Abortion
df$abortion1 <- abs(df$CC18_321a-1)
df$abortion2 <- abs(df$CC18_321b-2)
df$abortion3 <- abs(df$CC18_321c-2)
df$abortion4 <- abs(df$CC18_321d-2)
df$abortion5 <- abs(df$CC18_321e-2)
df$abortion6 <- abs(df$CC18_321f-2)
## State -- factor
df$state <- df$inputstate
df$state <- factor(df$state, levels = list_states_num, labels = list_states_abb, ordered = TRUE)
## Gender -- dichotomous (-0.5 Female, +0.5 Male)
df$male <- abs(df$gender-2)-0.5
## ethnicity -- factor
df$ethnicity <- factor(df$race,
levels = 1:8,
labels = c("White", "Black", "Hispanic", "Asian", "Native American", "Mixed", "Other", "Middle Eastern"),
ordered = TRUE)
df$ethnicity <- fct_collapse(df$ethnicity, "Other" = c("Asian", "Other", "Middle Eastern", "Mixed", "Native American"))
## Age -- cut into factor
df$age <- 2018 - df$birthyr
df$age <- cut(as.integer(df$age), breaks = c(0, 29, 39, 49, 59, 69, 120),
labels = c("18-29","30-39","40-49","50-59","60-69","70+"),
ordered_result = TRUE)
## Education -- factor
df$educ <- factor(as.integer(df$educ),
levels = 1:6,
labels = c("No HS", "HS", "Some college", "Associates", "4-Year College", "Post-grad"), ordered = TRUE)
df$educ <- fct_collapse(df$educ, "Some college" = c("Some college", "Associates"))
## ideology -- factor
df$ideology <- factor(as.integer(df$ideo5),
levels = 1:6,
labels = c("Very Liberal", "Liberal", "Moderate", "Conservative", "Very Conservative", "Not Sure"), ordered = TRUE)
# Clean and remove NAs
df <- df %>% select(starts_with("abortion"), state, ethnicity, male, age, educ, ideology) %>%
drop_na(state, ethnicity, male, age, educ)
}
df_all <- read_csv("data_public/chapter1/data/cces18_common_vv.csv.gz")
list_states_abb <- datasets::state.abb
list_states_num <- c(1,2,4,5,6,8,9,10,12,13,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,44,45,46,47,48,49,50,51,53,54,55,56)
df_all <- clean_cces(df_all, list_states_abb, list_states_num)
set.seed(1010)
df <- df_all %>% sample_n(5000)
df$subject <- 1:nrow(df)
```
```{r, warning=FALSE, include = FALSE}
statelevel_predictors <- read_csv('data_public/chapter1/data/statelevel_predictors.csv')
statelevel_predictors$region <- factor(statelevel_predictors$region, ordered = TRUE)
statelevel_predictors$state <- factor(statelevel_predictors$state, levels = levels(df$state), ordered = TRUE)
statelevel_predictors$repvote <- (statelevel_predictors$repvote - mean(statelevel_predictors$repvote))/sd(statelevel_predictors$repvote)
df <- left_join(df, statelevel_predictors)
```
```{r, include = FALSE}
postrat_df <- read_csv("data_public/chapter1/data/poststrat_df.csv")
postrat_df$state <- factor(postrat_df$state, levels = list_states_abb, labels = list_states_abb, ordered = TRUE)
postrat_df$ethnicity <- factor(postrat_df$eth, levels = levels(df$ethnicity), ordered = TRUE)
postrat_df$age <- factor(postrat_df$age, levels = levels(df$age), ordered = TRUE)
postrat_df$educ <- factor(postrat_df$educ, levels = levels(df$educ), ordered = TRUE)
postrat_df <- postrat_df %>% arrange(state, age, educ, ethnicity, male)
```
```{r, warning=FALSE, message=FALSE, eval=FALSE}
# We skip reading the data, as the process is exactly the same as in chapter 1 except for reading six questions
# in the CCES instead of only one. See Github repo for the entire code.
# Melt df for Stan (drop_na removes the missing cases)
df_melted <- df %>% select(starts_with("abortion"), state, ethnicity, age, educ, male, region, subject) %>%
melt(id.vars = c("state", "age", "ethnicity", "educ", "male", "region", "subject")) %>% drop_na()
# Prepare data for Stan
data <- list(J = length(unique(df_melted$subject)),
K = length(unique(df_melted$variable)),
N = nrow(df_melted),
S = nrow(statelevel_predictors),
P = nrow(postrat_df),
participant = as.numeric(df_melted$subject),
question = as.numeric(df_melted$variable),
state = as.numeric(df_melted$state),
age = as.numeric(df_melted$age),
ethnicity = as.numeric(df_melted$ethnicity),
educ = as.numeric(df_melted$educ),
male = as.numeric(df_melted$male),
region = as.numeric(statelevel_predictors$region),
repvote = statelevel_predictors$repvote,
postrat_state = as.numeric(postrat_df$state),
postrat_age = as.numeric(postrat_df$age),
postrat_ethnicity = as.numeric(postrat_df$ethnicity),
postrat_educ = as.numeric(postrat_df$educ),
postrat_male = postrat_df$male,
y = df_melted$value)
# Fit model
fit_id <- stan_model("data_public/chapter3/idealpoint.stan")
fit <- sampling(fit_id, data = data, iter = 2000, warmup = 1000, chains = 5,
control = list(adapt_delta = 0.99, max_treedepth = 12),
refresh = 25)
```
```{r, warning=FALSE, message=FALSE, echo=FALSE}
# We skip reading the data, as the process is exactly the same as in chapter 1 except for reading six questions
# in the CCES instead of only one. See Github repo for the entire code.
# Melt df for Stan (drop_na removes the missing cases)
df_melted <- df %>% select(starts_with("abortion"), state, ethnicity, age, educ, male, region, subject) %>%
melt(id.vars = c("state", "age", "ethnicity", "educ", "male", "region", "subject")) %>% drop_na()
# Prepare data for Stan
data <- list(J = length(unique(df_melted$subject)),
K = length(unique(df_melted$variable)),
N = nrow(df_melted),
S = nrow(statelevel_predictors),
P = nrow(postrat_df),
participant = as.numeric(df_melted$subject),
question = as.numeric(df_melted$variable),
state = as.numeric(df_melted$state),
age = as.numeric(df_melted$age),
ethnicity = as.numeric(df_melted$ethnicity),
educ = as.numeric(df_melted$educ),
male = as.numeric(df_melted$male),
region = as.numeric(statelevel_predictors$region),
repvote = statelevel_predictors$repvote,
postrat_state = as.numeric(postrat_df$state),
postrat_age = as.numeric(postrat_df$age),
postrat_ethnicity = as.numeric(postrat_df$ethnicity),
postrat_educ = as.numeric(postrat_df$educ),
postrat_male = postrat_df$male,
y = df_melted$value)
# Only train if train = TRUE; if not, load from fit_idealpoint.rds
train = FALSE
if(train){
fit_id <- stan_model("data_public/chapter3/idealpoint.stan")
fit <- sampling(fit_id, data = data, iter = 2000, warmup = 1000, chains = 5,
control = list(adapt_delta = 0.99, max_treedepth = 12),
refresh = 25)
saveRDS(fit, file = "data_public/chapter3/models/fit_idealpoint.rds")
} else {
fit <- readRDS("data_public/chapter3/models/fit_idealpoint.rds")
}
# Extract draws as dataframe
df_fit <- rstan::extract(fit)
```
### Initial Results
We can visualize the posterior distribution for the estimated $\alpha_j^{adj}$ of the first five participants:
```{r, echo=FALSE, fig.align = "center", fig.height=3.5, fig.width=6, warning=FALSE}
toplot <- data.frame(df_fit$alpha_adj[,1:5])
colnames(toplot) <- c("alpha1", "alpha2","alpha3","alpha4","alpha5")
ggplot(data = melt(toplot, id.vars = NULL), aes(x = value)) + geom_histogram(bins = 80) +
facet_grid(rows = vars(variable), labeller = labeller(variable = c(alpha1 = "alpha 1",
alpha2 = "alpha 2",
alpha3 = "alpha 3",
alpha4 = "alpha 4",
alpha5 = "alpha 5"))) +
theme_bw() + xlab("") + ylab("") +
xlim(c(-4, 4))
```
Conversely, we can visualize the distribution of $\alpha_j^{adj}$ for a random subset of the posterior draws:
```{r, echo=FALSE, fig.align = "center", fig.height=3, fig.width=6, warning=FALSE}
toplot <- data.frame(t(df_fit$alpha_adj[sample(nrow(df_fit$alpha_adj),size=50),]))
ggplot(data = melt(toplot, id.vars = NULL), aes(x = value, color = variable)) + geom_density(alpha = 0.25) + scale_colour_grey() + guides(color=FALSE) + theme_bw() + ylab("") + xlab(latex2exp::TeX("$\\alpha^{adj}$")) + xlim(c(-3, 3))
```
As a first check that the ideal points $\alpha_j^{adj}$ estimated by the model are capturing a meaningful latent variable, we correlate them with the reported ideology in the CCES by each participant $j$. This results in a correlation of 0.53.
```{r, echo=FALSE, eval=FALSE, warning=FALSE, message=FALSE}
round(cor(as.numeric(df$ideology), colMeans(df_fit$alpha_adj)), 2)
```
We can plot the distribution for a one single draw of $\alpha_j^{adj}$, but selecting only CCES respondents from California and Tennessee, which provides an approximation of the between-state and within-state variations. Not surprisingly, individuals from Tennessee tend to have higher ideal points.
```{r, echo=FALSE, fig.align = "center", fig.height=3, fig.width=5, warning=FALSE, message=FALSE}
ggplot(data = data.frame()) +
geom_density(data = data.frame(x = df_fit$alpha_adj[1, df$state=="CA"]), aes(x = x), fill = "blue", alpha = 0.5) +
geom_density(data = data.frame(x = df_fit$alpha_adj[1, df$state=="TN"]), aes(x = x), fill = "red", alpha = 0.5) +
scale_x_continuous(limits = c(-3, 3)) +
theme_bw() + xlab(latex2exp::TeX("$\\alpha^{adj}$")) + ylab("") +
annotate("text", x = 2, y = 0.35, label = "Tennessee", color = "red") +
annotate("text", x = -1.7, y = 0.35, label = "California", color = "blue")
```
Lastly, we can also visualize the probability of supporting each statement for the potential values of $\alpha_j^{adj}$.
```{r, echo=FALSE, fig.align = "center", fig.height=7, fig.width=12}
questions <- c("Always allow a woman to obtain an abortion as a matter of choice (Reversed)",
"Permit abortion ONLY in case of rape, incest or when the woman’s life is in danger",
"Ban abortions after the 20th week of pregnancy",
"Allow employers to decline coverage of abortions in insurance plans",
"Prohibit the expenditure of funds authorized or appropriated by federal law for any abortion",
"Make abortions illegal in all circumstances")
plotlogistic <- function(question, n_draws){
draws <- sample(1:nrow(df_fit$beta_adj), n_draws)
outcome <- matrix(seq(-5, 5, by = .1))
for(draw in draws){
outcome <- cbind(outcome, df_fit$gamma_adj[draw, question] * (seq(-5, 5, by = .1) - df_fit$beta_adj[draw, question]))
}
outcome <- melt(data.frame(outcome), id.vars = "X1")
outcome$value <- plogis(outcome$value)
plot <- ggplot(data = outcome, aes(x = X1, y = value, color = variable)) + geom_line() + scale_colour_grey() + guides(color="none") +
xlab(latex2exp::TeX("$\\alpha^{adj}$")) + ylab(latex2exp::TeX("$P(y = 1)$")) + ggtitle(questions[question]) + theme_bw() + theme(plot.title = element_text(size=10))
return(plot)
}
grid.arrange(plotlogistic(1, 50), plotlogistic(2, 50), plotlogistic(3, 50), plotlogistic(4, 50), plotlogistic(5, 50), plotlogistic(6, 50), ncol = 2)
```
## The Abortion Opposition Index for US States
Assuming our poststratification table has $T$ cells that reflect different geographic-demographic combinations, the ideal point model allows to estimate the expected ability $\mu_{\alpha_t}$ for each of these combinations. Before poststratification, we need to transform this $\mu_{\alpha_t}$ into $\mu_{\alpha^{adj}_t}$ by considering that $\mu_{\alpha^{adj}_t} = \frac{\mu_{\alpha_t} - \bar{\alpha}}{s_{\alpha}}$. In order to do this we:
1. Draw with replacement $L$ individuals from the poststratification table (weighting by $N$, the number of people in each cell).
2. Calculate $\mu_{\alpha_l}$ for each subject $l$, and then add some random noise centered at zero and with standard deviation $\sigma_\alpha$ (which was estimated in the model). This simulates the $\alpha_l$ for a random sample of $L$ subjects that come from the population defined by the poststratification table.
3. Given $\alpha_l$, calculate $\bar{\alpha}_l$ and $s_{\alpha_l}$. These values correspond to the estimated average and standard deviation for the abilities in the population defined by the poststratification table.
4. Calculate $\mu_{\alpha^{adj}_t} = \frac{\mu_{\alpha_t} - \bar{\alpha}_l}{s_{\alpha_l}}$
This process is repeated for each draw of the posterior distribution. If we have $D$ draws and $T$ poststratification cells, $\mu_{\alpha^{adj}_t}$ will be a $D \times T$ matrix.
```{r}
# Calculating mu_alpha_adj
ndraws <- nrow(df_fit$alpha_pred_raw)
L <- 10000
mu_alpha_adj <- matrix(NA, nrow = ndraws, ncol = 12000)
for(d in 1:ndraws){
mu_alpha <- df_fit$mu_alpha[d] + df_fit$alpha_pred_raw[d,]
sample_alphas_pop <- sample(mu_alpha, size = L, prob = postrat_df$n/sum(postrat_df$n), replace = TRUE)
sample_alphas_pop <- sample_alphas_pop + rnorm(L, 0, df_fit$sigma_alpha[d])
mean_alpha <- mean(sample_alphas_pop)
sd_alpha <- sd(sample_alphas_pop)
mu_alpha_adj[d,] <- (mu_alpha - mean_alpha) / sd_alpha
}
```
$\mu_{\alpha^{adj}_t}$ can be poststratified as usual in order to obtain state-level ideal points that reflect what we may refer as the _Abortion Opposition Index_. It is important to clarify that these final sub-national estimates are relative to the national level (which is, as defined in the model, equal to zero).
```{r}
# Poststratification
national_level <- mu_alpha_adj %*% postrat_df$n / sum(postrat_df$n)
df_state_idealpoint <- data.frame(state = rep(NA, length(levels(df$state))),
idealpoint_mean = NA,
idealpoint_sd = NA)
i = 1
for(s in levels(df$state)){
state_estimates <- (mu_alpha_adj[, which(postrat_df$state==s)] %*% postrat_df$n[which(postrat_df$state==s)]/
sum(postrat_df$n[which(postrat_df$state==s)]) )
df_state_idealpoint$state[i] <- s
df_state_idealpoint$idealpoint_mean[i] <- mean(state_estimates)
df_state_idealpoint$idealpoint_sd[i] <- sd(state_estimates)
i = i + 1
}
```
```{r, fig.height= 3, fig.width=12, echo=FALSE, fig.align = "center"}
df_state_idealpoint$state <- fct_reorder(df_state_idealpoint$state, statelevel_predictors$repvote)
ggplot(data=df_state_idealpoint) +
geom_hline(aes(yintercept = 0)) +
geom_point(aes(x=state, y=idealpoint_mean)) +
geom_errorbar(aes(ymin=idealpoint_mean - 2*idealpoint_sd,
ymax=idealpoint_mean + 2*idealpoint_sd,
x=state), alpha=.5, width = 0) +
theme_bw() +
labs(x="States",y="Abortion Opposition Index")+
theme(legend.position="none",
axis.title=element_text(size=10),
axis.text.y=element_text(size=10),
axis.text.x=element_text(angle=90,size=8, vjust=0.3),
legend.title=element_text(size=10),
legend.text=element_text(size=10))
```
The correlation between these state-level estimates and Republican voteshare in the 2016 election is `r round(cor(df_state_idealpoint$idealpoint_mean, statelevel_predictors$repvote), 2)`.
```{r, message=FALSE, warning=FALSE, echo=FALSE, fig.height=5, fig.width=9, fig.align = "center"}
states_map <- us_map(regions = "states")
state_df_melted <- df_state_idealpoint %>% select(state, idealpoint_mean)
states_map <- left_join(states_map, state_df_melted, by = c("abbr" = "state")) %>% drop_na()
ggplot(states_map, aes(x = x, y = y, group = group)) +
geom_polygon(colour = "lightgray") +
geom_polygon(aes(fill = idealpoint_mean)) + theme_void() +
scale_fill_gradient2(midpoint = 0, limits = c(-0.6, 0.6), breaks = c(-0.5, -0.25, 0, 0.25, 0.5),
name = "Abortion Opposition Index", low = muted("blue"), high = muted("red")) +
theme(legend.margin=margin(l = 0.5, unit='cm'))
```
### Comparison with simple sum
A simpler approach for obtaining estimates about the latent abortion opposition is to consider the sum of the six questions for each respondent as the outcome, fitting a multilevel linear regression and poststratifying as usual.
```{r, echo = TRUE, warning=FALSE}
df$abortion_score <- rowMeans(select(df, abortion1, abortion2, abortion3, abortion4, abortion5, abortion6), na.rm = TRUE)
train = FALSE
if(train){
fit_sum <- stan_glmer(abortion_score ~ (1 | state) + (1 | ethnicity) + (1 | age) + (1 | educ) + male + repvote + (1 | region),
data = df,
prior = normal(0, 1, autoscale = TRUE),
prior_covariance = decov(scale = 0.50),
adapt_delta = 0.99,
seed = 1010)
saveRDS(fit_sum, file = "data_public/chapter3/models/fit_sum.rds")
} else {
fit_sum <- readRDS(file = "data_public/chapter3/models/fit_sum.rds")
}
P <- posterior_epred(fit_sum, newdata = left_join(postrat_df, statelevel_predictors))
df_state_sum <- data.frame(state = levels(postrat_df$state),
sum_mean = NA,
sum_sd = NA,
sum_mean_relative = NA)
national_level <- P %*% postrat_df$n / sum(postrat_df$n)
for(i in 1:length(levels(postrat_df$state))) {
filtering_condition <- which(postrat_df$state == as.character(df_state_sum$state[i]))
P_filtered <- P[ ,filtering_condition]
k_filtered <- postrat_df[filtering_condition, ]$n
poststrat_prob_state <- P_filtered %*% k_filtered / sum(k_filtered)
df_state_sum$sum_mean[i] <- mean(poststrat_prob_state)
df_state_sum$sum_sd[i] <- sd(poststrat_prob_state)
}
```
```{r, fig.height= 3, fig.width=12, echo=FALSE, fig.align = "center", warning=FALSE, message=FALSE}
df_state_sum$state <- fct_reorder(df_state_sum$state, statelevel_predictors$repvote)
ggplot(data=df_state_sum) +
geom_point(aes(x=state, y=sum_mean)) +
geom_errorbar(aes(ymin=sum_mean - 2*sum_sd,
ymax=sum_mean + 2*sum_sd,
x=state), alpha=.5, width = 0) +
scale_y_continuous(expand=c(0,0)) + #limits = c(1, 4),
theme_bw()+
labs(x="States",y="Abortion Opposition Score")+
theme(legend.position="none",
axis.title=element_text(size=10),
axis.text.y=element_text(size=10),
axis.text.x=element_text(angle=90,size=8, vjust=0.3),
legend.title=element_text(size=10),
legend.text=element_text(size=10))
joined_df <- left_join(df_state_idealpoint, df_state_sum)
```
These results are very similar to what we obtained with the ideal-point model. In fact, the state-level point estimates produced by the two methods have a correlation of `r round(cor(joined_df$idealpoint_mean, joined_df$sum_mean), 4)`. Still, the ideal point model results in more precise results, with an average absolute $t$ of `r round(mean(abs(joined_df$idealpoint_mean/joined_df$idealpoint_sd)), 2)` that is higher than the `r round(mean(abs(joined_df$idealpoint_mean/joined_df$sum_sd)), 2)` produced by naive sum of question outcomes.
### Fake-data simulation
We expect the ideal point model to be similar to the naive sum approach when all the questions are equally relevant to the latent variable. Conversely, when some of the questions are more relevant than others we expect the ideal point model to perform better both in terms of reduced error and tighter standard errors. To demonstrate this we use fake data simulation. We draw 2,500 individuals according to the weights provided by the poststratification table, calculate their true ideal point based on pre-specified values for the multilevel predictors, and then define six questions. In one case we will use six questions which are approximately equally relevant ($\mu^{\gamma} = 2$, $\sigma^{\gamma} = 0.2$), while in the other we will use six questions with very different discrimination parameters ($\mu^{\gamma} = 2$, $\sigma^{\gamma} = 0.8$).
#### Questions with similar discrimination parameters
When we consider six questions with little variation across their discrimination parameters, the results for the ideal point MRP and the sum MRP are very similar both in terms of MAE and mean SE. The ideal point MRP estimates and the true values are in the same scale, but the naive sum MRP are not. In order to compare them we standarize the subnational estimates that result from the three methods.
```{r, echo = FALSE, warning=FALSE, message=FALSE}
postrat_df_numeric <- data.frame(sapply(left_join(postrat_df, statelevel_predictors), as.numeric))
set.seed(1010)
df_fake <- postrat_df_numeric %>%
select(state, repvote, region, age, educ, male, ethnicity) %>%
sample_n(size = 2500, replace = TRUE, weight = (postrat_df$n)/sum(postrat_df$n))
# Similuate dataframe with state-level characteristics and
# obtain state-level effects
statelevel <- postrat_df_numeric %>% select(state, repvote, region) %>% distinct()
statelevel$effect <- 0.25*statelevel$repvote + c(-.02, -0.04, 0.06, 0.01)[statelevel$region] + rnorm(nrow(statelevel), 0, 0.05)
# Simulate ideal points
df_fake$idealpoint <- statelevel$effect[df_fake$state] +
c(0.054, -0.13, 0.05, 0.02)[df_fake$ethnicity] +
c(-0.17, 0.10, -0.06, 0.06, 0.10, 0.17)[df_fake$age] +
c(0.24, 0.16, 0.06, -0.13, -0.32)[df_fake$educ] +
0.17*df_fake$male +
rnorm(nrow(df_fake), 0, 1)
# Simulate ideal points for poststratification table
postrat_df_numeric$idealpoint <- statelevel$effect[postrat_df_numeric$state] +
c(0.054, -0.13, 0.05, 0.02)[postrat_df_numeric$ethnicity] +
c(-0.17, 0.10, -0.06, 0.06, 0.10, 0.17)[postrat_df_numeric$age] +
c(0.24, 0.16, 0.06, -0.13, -0.32)[postrat_df_numeric$educ] +
0.17*postrat_df_numeric$male
gammas <- c(2, 2.2, 1.9, 1.7, 2.1, 2)
betas <- c(0, 1, -1, 0.5, -0.5, 0)
df_fake$question1 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[1]*(df_fake$idealpoint - betas[1])))
df_fake$question2 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[2]*(df_fake$idealpoint - betas[2])))
df_fake$question3 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[3]*(df_fake$idealpoint - betas[3])))
df_fake$question4 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[4]*(df_fake$idealpoint - betas[4])))
df_fake$question5 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[5]*(df_fake$idealpoint - betas[5])))
df_fake$question6 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[6]*(df_fake$idealpoint - betas[6])))
national_level_true <- postrat_df_numeric$idealpoint %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
df_state_true <- data.frame(state = statelevel$state, true = NA)
for(i in df_state_true$state){
filtering_condition <- which(postrat_df_numeric$state == df_state_true$state[i])
df_state_true$true[i] <- (postrat_df_numeric$idealpoint[filtering_condition] %*% postrat_df_numeric$n[filtering_condition] /
sum(postrat_df_numeric$n[filtering_condition])) - national_level_true
}
true_mean <- mean(df_state_true$true)
true_sd <- sd(df_state_true$true)
df_state_true$true <- (df_state_true$true - true_mean) / true_sd
df_state_true$state <- fct_reorder(factor(df_state_true$state), statelevel_predictors$repvote)
```
```{r, fig.height=3.5, fig.width=12, fig.align='center', echo = FALSE, warning=FALSE, message=FALSE}
df_fake$abortion_score <- rowSums(select(df_fake, starts_with("question")))
if(FALSE){
fit_sum <- stan_glmer(abortion_score ~ (1 | state) + (1 | ethnicity) + (1 | age) + (1 | educ) + male + repvote + (1 | region),
data = df_fake,
prior = normal(0, 1, autoscale = TRUE),
prior_covariance = decov(scale = 0.50),
adapt_delta = 0.99,
seed = 1010)
saveRDS(fit_sum, file = "data_public/chapter3/models/fakedata/fit_fakedata1_sum.rds")
} else {
fit_sum <- readRDS("data_public/chapter3/models/fakedata/fit_fakedata1_sum.rds")
}
P <- posterior_epred(fit_sum,
newdata = postrat_df_numeric)
df_state_sum <- data.frame(state = unique(postrat_df_numeric$state),
sum_mean = NA,
sum_sd = NA,
true = NA)
national_level <- P %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
for(i in unique(postrat_df_numeric$state)){
filtering_condition <- which(postrat_df_numeric$state == df_state_sum$state[i])
P_filtered <- P[ ,filtering_condition]
k_filtered <- postrat_df[filtering_condition, ]$n
poststrat_prob_state <- P_filtered %*% k_filtered / sum(k_filtered) - national_level
df_state_sum$sum_mean[i] <- mean(poststrat_prob_state)
df_state_sum$sum_sd[i] <- sd(poststrat_prob_state)
}
st_mean <- mean(df_state_sum$sum_mean)
st_sd <- sd(df_state_sum$sum_mean)
df_state_sum$sum_mean <- (df_state_sum$sum_mean - st_mean) / st_sd
df_state_sum$sum_sd <- df_state_sum$sum_sd / st_sd
df_state_sum$state <- fct_reorder(factor(df_state_sum$state), statelevel_predictors$repvote)
df_fake$subject <- 1:nrow(df_fake)
df_melted <- df_fake %>% select(starts_with("question"), state, ethnicity, age, educ, male, region, subject) %>%
melt(id.vars = c("state", "age", "ethnicity", "educ", "male", "region", "subject"))
data <- list(J = length(unique(df_melted$subject)),
K = length(unique(df_melted$variable)),
N = nrow(df_melted),
S = nrow(statelevel_predictors),
P = nrow(postrat_df),
participant = as.numeric(df_melted$subject),
question = as.numeric(df_melted$variable),
state = as.numeric(df_melted$state),
age = as.numeric(df_melted$age),
ethnicity = as.numeric(df_melted$ethnicity),
educ = as.numeric(df_melted$educ),
male = as.numeric(df_melted$male),
region = as.numeric(statelevel_predictors$region),
repvote = statelevel_predictors$repvote,
postrat_state = as.numeric(postrat_df_numeric$state),
postrat_age = as.numeric(postrat_df_numeric$age),
postrat_ethnicity = as.numeric(postrat_df_numeric$ethnicity),
postrat_educ = as.numeric(postrat_df_numeric$educ),
postrat_male = postrat_df_numeric$male,
y = df_melted$value)
if(FALSE){
fit_id <- stan_model("data_public/chapter3/idealpoint.stan")
fit_relevant <- sampling(fit_id, data = data, iter = 1000, warmup = 400, chains = 5,
control = list(adapt_delta = 0.99, max_treedepth = 12),
refresh = 25)
saveRDS(fit_relevant, file = "data_public/chapter3/models/fakedata/fit_fakedata1_idealpoint.rds")
} else{
fit_relevant <- readRDS("data_public/chapter3/models/fakedata/fit_fakedata1_idealpoint.rds")
}
df_fit <- rstan::extract(fit_relevant)
ndraws <- nrow(df_fit$alpha_pred_raw)
L <- 5000
mu_alpha_adj <- matrix(NA, nrow = ndraws, ncol = 12000)
for(d in 1:ndraws){
mu_alpha <- df_fit$mu_alpha[d] + df_fit$alpha_pred_raw[d,]
sample_alphas_pop <- sample(mu_alpha, size = L, prob = postrat_df$n/sum(postrat_df$n), replace = TRUE)
sample_alphas_pop <- sample_alphas_pop + rnorm(L, 0, df_fit$sigma_alpha[d])
mean_alpha <- mean(sample_alphas_pop)
sd_alpha <- sd(sample_alphas_pop)
mu_alpha_adj[d,] <- (mu_alpha - mean_alpha) / sd_alpha
}
national_level <- mu_alpha_adj %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
df_state_idealpoint <- data.frame(state = 1:max(postrat_df_numeric$state),
idealpoint_mean = NA,
idealpoint_sd = NA)
for(s in 1:max(postrat_df_numeric$state)){
state_estimates <- (mu_alpha_adj[, which(postrat_df_numeric$state==s)] %*% postrat_df$n[which(postrat_df_numeric$state==s)]) /
sum(postrat_df_numeric$n[which(postrat_df_numeric$state==s)])
df_state_idealpoint$state[s] <- s
df_state_idealpoint$idealpoint_mean[s] <- mean(state_estimates)
df_state_idealpoint$idealpoint_sd[s] <- sd(state_estimates)
}
ip_mean <- mean(df_state_idealpoint$idealpoint_mean)
ip_sd <- sd(df_state_idealpoint$idealpoint_mean)
df_state_idealpoint$idealpoint_mean <- (df_state_idealpoint$idealpoint_mean - ip_mean) / ip_sd
df_state_idealpoint$idealpoint_sd <- (df_state_idealpoint$idealpoint_sd)/ ip_sd
df_state_idealpoint$state <- fct_reorder(factor(df_state_idealpoint$state), statelevel_predictors$repvote)
ggplot(data=df_state_idealpoint) +
geom_hline(aes(yintercept = 0)) +
geom_point(aes(x=state, y=idealpoint_mean), color = "#7B1CE3", alpha = 1) +
geom_errorbar(aes(ymin=idealpoint_mean - 2*idealpoint_sd,
ymax=idealpoint_mean + 2*idealpoint_sd,
x=state), alpha=.5, width = 0, color = "#7B1CE3", alpha = 1) +
geom_point(data = df_state_sum, aes(x=state, y=sum_mean), color = "#E37B1C", alpha = 0.7) +
geom_errorbar(data = df_state_sum, aes(ymin=sum_mean - 2*sum_sd,
ymax=sum_mean + 2*sum_sd,
x=state), alpha=.5, width = 0, color = "#E37B1C", alpha = 0.7) +
geom_point(data = df_state_true, aes(x=state, y=true), color = "#1CE37B", alpha = 1) +
scale_y_continuous(expand=c(0,0)) +
theme_bw() +
labs(x="States",y="Standardized Index")+
theme(legend.position="none",
axis.title=element_text(size=10),
axis.text.y=element_text(size=10),
axis.text.x=element_text(angle=90,size=8, vjust=0.3),
legend.title=element_text(size=10),
legend.text=element_text(size=10)) +
annotate("text", x = 7, y = 3, color = "#7B1CE3", label = paste0("MAE for ideal point model: ", round(mean(abs(df_state_idealpoint$idealpoint_mean - df_state_true$true)), 2))) +
annotate("text", x = 7, y = 2.5, color = "#7B1CE3", label = paste0("Mean SE for ideal point model: ", round(mean(df_state_idealpoint$idealpoint_sd), 2))) +
annotate("text", x = 7, y = 2, color = "#E37B1C", label = paste0("MAE for sum model: ", round(mean(abs(df_state_sum$sum_mean - df_state_true$true)), 2))) +
annotate("text", x = 7, y = 1.5, color = "#E37B1C", label = paste0("Mean SE for sum model: ", round(mean(df_state_sum$sum_sd), 2)))
```
#### Questions with different discrimination values
When the questions have very different $\gamma_k$, the advantage of ideal point MRP is more remarkable, both in terms of lower mean SE and smaller Mean Absolute Error.
```{r, echo = FALSE, warning=FALSE, message=FALSE}
postrat_df_numeric <- data.frame(sapply(left_join(postrat_df, statelevel_predictors), as.numeric))
set.seed(1010)
df_fake <- postrat_df_numeric %>%
select(state, repvote, region, age, educ, male, ethnicity) %>%
sample_n(size = 2500, replace = TRUE, weight = (postrat_df$n)/sum(postrat_df$n))
# Similuate dataframe with state-level characteristics and
# obtain state-level effects
statelevel <- postrat_df_numeric %>% select(state, repvote, region) %>% distinct()
statelevel$effect <- 0.25*statelevel$repvote + c(-.02, -0.04, 0.06, 0.01)[statelevel$region] + rnorm(nrow(statelevel), 0, 0.05)
# Simulate ideal points
df_fake$idealpoint <- statelevel$effect[df_fake$state] +
c(0.054, -0.13, 0.05, 0.02)[df_fake$ethnicity] +
c(-0.17, 0.10, -0.06, 0.06, 0.10, 0.17)[df_fake$age] +
c(0.24, 0.16, 0.06, -0.13, -0.32)[df_fake$educ] +
0.17*df_fake$male +
rnorm(nrow(df_fake), 0, 1)
# Simulate ideal points for poststratification table
postrat_df_numeric$idealpoint <- statelevel$effect[postrat_df_numeric$state] +
c(0.054, -0.13, 0.05, 0.02)[postrat_df_numeric$ethnicity] +
c(-0.17, 0.10, -0.06, 0.06, 0.10, 0.17)[postrat_df_numeric$age] +
c(0.24, 0.16, 0.06, -0.13, -0.32)[postrat_df_numeric$educ] +
0.17*postrat_df_numeric$male
gammas <- c(2.3, 3, 1.3, 0.3, 2.8, 1.7)
betas <- c(0, 1, -1, 0.5, -0.5, 0)
df_fake$question1 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[1]*(df_fake$idealpoint - betas[1])))
df_fake$question2 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[2]*(df_fake$idealpoint - betas[2])))
df_fake$question3 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[3]*(df_fake$idealpoint - betas[3])))
df_fake$question4 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[4]*(df_fake$idealpoint - betas[4])))
df_fake$question5 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[5]*(df_fake$idealpoint - betas[5])))
df_fake$question6 <- rbinom(nrow(df_fake), size = 1, prob = plogis(gammas[6]*(df_fake$idealpoint - betas[6])))
national_level_true <- postrat_df_numeric$idealpoint %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
df_state_true <- data.frame(state = statelevel$state, true = NA)
for(i in df_state_true$state){
filtering_condition <- which(postrat_df_numeric$state == df_state_true$state[i])
df_state_true$true[i] <- (postrat_df_numeric$idealpoint[filtering_condition] %*% postrat_df_numeric$n[filtering_condition] /
sum(postrat_df_numeric$n[filtering_condition])) - national_level_true
}
true_mean <- mean(df_state_true$true)
true_sd <- sd(df_state_true$true)
df_state_true$true <- (df_state_true$true - true_mean) / true_sd
df_state_true$state <- fct_reorder(factor(df_state_true$state), statelevel_predictors$repvote)
```
```{r, fig.height=3.5, fig.width=12, fig.align='center', echo = FALSE, warning=FALSE, message=FALSE}
df_fake$abortion_score <- rowSums(select(df_fake, starts_with("question")))
if(FALSE){
fit_sum <- stan_glmer(abortion_score ~ (1 | state) + (1 | ethnicity) + (1 | age) + (1 | educ) + male + repvote + (1 | region),
data = df_fake,
prior = normal(0, 1, autoscale = TRUE),
prior_covariance = decov(scale = 0.50),
adapt_delta = 0.99,
seed = 1010)
saveRDS(fit_sum, file = "data_public/chapter3/models/fakedata/fit_fakedata2_sum.rds")
} else {
fit_sum <- readRDS("data_public/chapter3/models/fakedata/fit_fakedata2_sum.rds")
}
P <- posterior_epred(fit_sum,
newdata = postrat_df_numeric)
df_state_sum <- data.frame(state = unique(postrat_df_numeric$state),
sum_mean = NA,
sum_sd = NA,
true = NA)
national_level <- P %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
for(i in unique(postrat_df_numeric$state)){
filtering_condition <- which(postrat_df_numeric$state == df_state_sum$state[i])
P_filtered <- P[ ,filtering_condition]
k_filtered <- postrat_df[filtering_condition, ]$n
poststrat_prob_state <- P_filtered %*% k_filtered / sum(k_filtered) - national_level
df_state_sum$sum_mean[i] <- mean(poststrat_prob_state)
df_state_sum$sum_sd[i] <- sd(poststrat_prob_state)
}
st_mean <- mean(df_state_sum$sum_mean)
st_sd <- sd(df_state_sum$sum_mean)
df_state_sum$sum_mean <- (df_state_sum$sum_mean - st_mean) / st_sd
df_state_sum$sum_sd <- df_state_sum$sum_sd / st_sd
df_state_sum$state <- fct_reorder(factor(df_state_sum$state), statelevel_predictors$repvote)
df_fake$subject <- 1:nrow(df_fake)
df_melted <- df_fake %>% select(starts_with("question"), state, ethnicity, age, educ, male, region, subject) %>%
melt(id.vars = c("state", "age", "ethnicity", "educ", "male", "region", "subject"))
data <- list(J = length(unique(df_melted$subject)),
K = length(unique(df_melted$variable)),
N = nrow(df_melted),
S = nrow(statelevel_predictors),
P = nrow(postrat_df),
participant = as.numeric(df_melted$subject),
question = as.numeric(df_melted$variable),
state = as.numeric(df_melted$state),
age = as.numeric(df_melted$age),
ethnicity = as.numeric(df_melted$ethnicity),
educ = as.numeric(df_melted$educ),
male = as.numeric(df_melted$male),
region = as.numeric(statelevel_predictors$region),
repvote = statelevel_predictors$repvote,
postrat_state = as.numeric(postrat_df_numeric$state),
postrat_age = as.numeric(postrat_df_numeric$age),
postrat_ethnicity = as.numeric(postrat_df_numeric$ethnicity),
postrat_educ = as.numeric(postrat_df_numeric$educ),
postrat_male = postrat_df_numeric$male,
y = df_melted$value)
if(FALSE){
fit_id <- stan_model("data_public/chapter3/idealpoint.stan")
fit_relevant <- sampling(fit_id, data = data, iter = 1000, warmup = 400, chains = 5,
control = list(adapt_delta = 0.99, max_treedepth = 12),
refresh = 25)
saveRDS(fit_relevant, file = "data_public/chapter3/models/fakedata/fit_fakedata2_idealpoint.rds")
} else{
fit_relevant <- readRDS("data_public/chapter3/models/fakedata/fit_fakedata2_idealpoint.rds")
}
df_fit <- rstan::extract(fit_relevant)
ndraws <- nrow(df_fit$alpha_pred_raw)
L <- 5000
mu_alpha_adj <- matrix(NA, nrow = ndraws, ncol = 12000)
for(d in 1:ndraws){
mu_alpha <- df_fit$mu_alpha[d] + df_fit$alpha_pred_raw[d,]
sample_alphas_pop <- sample(mu_alpha, size = L, prob = postrat_df$n/sum(postrat_df$n), replace = TRUE)
sample_alphas_pop <- sample_alphas_pop + rnorm(L, 0, df_fit$sigma_alpha[d])
mean_alpha <- mean(sample_alphas_pop)
sd_alpha <- sd(sample_alphas_pop)
mu_alpha_adj[d,] <- (mu_alpha - mean_alpha) / sd_alpha
}
national_level <- mu_alpha_adj %*% postrat_df_numeric$n / sum(postrat_df_numeric$n)
df_state_idealpoint <- data.frame(state = 1:max(postrat_df_numeric$state),
idealpoint_mean = NA,
idealpoint_sd = NA)
for(s in 1:max(postrat_df_numeric$state)){
state_estimates <- (mu_alpha_adj[, which(postrat_df_numeric$state==s)] %*% postrat_df$n[which(postrat_df_numeric$state==s)]) /
sum(postrat_df_numeric$n[which(postrat_df_numeric$state==s)])
df_state_idealpoint$state[s] <- s
df_state_idealpoint$idealpoint_mean[s] <- mean(state_estimates)
df_state_idealpoint$idealpoint_sd[s] <- sd(state_estimates)
}
ip_mean <- mean(df_state_idealpoint$idealpoint_mean)
ip_sd <- sd(df_state_idealpoint$idealpoint_mean)
df_state_idealpoint$idealpoint_mean <- (df_state_idealpoint$idealpoint_mean - ip_mean) / ip_sd
df_state_idealpoint$idealpoint_sd <- (df_state_idealpoint$idealpoint_sd)/ ip_sd
df_state_idealpoint$state <- fct_reorder(factor(df_state_idealpoint$state), statelevel_predictors$repvote)
ggplot(data=df_state_idealpoint) +
geom_hline(aes(yintercept = 0)) +
geom_point(aes(x=state, y=idealpoint_mean), color = "#7B1CE3", alpha = 1) +
geom_errorbar(aes(ymin=idealpoint_mean - 2*idealpoint_sd,
ymax=idealpoint_mean + 2*idealpoint_sd,
x=state), alpha=.5, width = 0, color = "#7B1CE3", alpha = 1) +
geom_point(data = df_state_sum, aes(x=state, y=sum_mean), color = "#E37B1C", alpha = 0.7) +
geom_errorbar(data = df_state_sum, aes(ymin=sum_mean - 2*sum_sd,
ymax=sum_mean + 2*sum_sd,
x=state), alpha=.5, width = 0, color = "#E37B1C", alpha = 0.7) +
geom_point(data = df_state_true, aes(x=state, y=true), color = "#1CE37B", alpha = 1) +
scale_y_continuous(expand=c(0,0)) +
theme_bw() +
labs(x="States",y="Standardized Index")+
theme(legend.position="none",
axis.title=element_text(size=10),
axis.text.y=element_text(size=10),
axis.text.x=element_text(angle=90,size=8, vjust=0.3),
legend.title=element_text(size=10),
legend.text=element_text(size=10)) +
annotate("text", x = 7, y = 3, color = "#7B1CE3", label = paste0("MAE for ideal point model: ", round(mean(abs(df_state_idealpoint$idealpoint_mean - df_state_true$true)), 2))) +
annotate("text", x = 7, y = 2.5, color = "#7B1CE3", label = paste0("Mean SE for ideal point model: ", round(mean(df_state_idealpoint$idealpoint_sd), 2))) +
annotate("text", x = 7, y = 2, color = "#E37B1C", label = paste0("MAE for sum model: ", round(mean(abs(df_state_sum$sum_mean - df_state_true$true)), 2))) +
annotate("text", x = 7, y = 1.5, color = "#E37B1C", label = paste0("Mean SE for sum model: ", round(mean(df_state_sum$sum_sd), 2)))
```
Lastly, we can see that the ideal point MRP has been able to recover the true $\gamma_k$ and $\beta_k$ for each question.
```{r, echo = FALSE}
data.frame(true_gamma = gammas,
estimated_gamma = round(colMeans(df_fit$gamma_adj), 1),
true_beta = betas,
estimated_beta = round(colMeans(df_fit$beta_adj), 1)) %>% kable(format = 'markdown')
```
## Estimating Support for Individual Questions
Based on the estimated $\mu^{\alpha}$, $A_{\rm s[j]}^{\rm state}$, $A_{\rm a[j]}^{\rm age}$, $A_{\rm r[j]}^{\rm ethnicity}$, $A_{\rm e[j]}^{\rm education}$, and $B^{\rm male}$ we can estimate $\mu_{\alpha_j}$, the average ability for each cell $j$ in the poststratification table. This was the quantity that previously we standardized into $\mu_{\alpha^{adj}_j}$ and used in the poststratification step, obtaining state-level estimates for the ideal points. These average ability estimates can instead be transformed with $logit^{-1}(\gamma_{k}^{adj}(\mu_{\alpha_j}^{adj} - \beta_{k}^{adj}))$. The result is an estimate of the probability of supporting question $k$ for the average ability corresponding to each poststratification cell.
### Mind the (Jensen's) gap
$\mu_{\alpha^{adj}_j}$ reflects the (standardized) average ideal point position for each poststratification cell, which can be transformed into the probability of the average person in this cell $j$ supporting a given statement $k$. However, this quantity is not particularly interesting for us. What we really need to estimate is the average probability that the individuals in cell $j$ support statement $k$. In a simplified example, what we have estimated is the probability that the average Texan supports a given statement. However, our goal is to obtain the average support of that statement for the people in Texas. For this, we need to consider that, for each poststratification cell $j$, $\alpha_j \sim N(\mu_{\alpha_j} \sigma_\alpha)$.
Naively using $\mu_{\alpha_j}$ or its standardized version, as we have done in the previous subsection, results in estimates that are too extreme. As a result of Jensen's inequality and the properties of the logistic function, if we use a nonlinear transformation $f(x) = logit^{-1}(g(x - b))$ (where $g>0$) on a random variable $X$ we will obtain that $f(E[X]) \leq E[f(X)]$ when $f(x)$ is convex (i.e. when $X - b < 0$) and $f(E[x]) \geq E[f(x)]$ when it is concave (i.e. when $X - b > 0$). We can show this by simulating multiple draws from $X \sim N(0, \sigma)$ and transforming them with $f(x) = logit^{-1}(x)$ (i.e. in our example, $b = 0$ and $g = 1$):
```{r, fig.height= 4, fig.width=7, echo=FALSE, fig.align = "center", warning=FALSE, message=FALSE}
x <- seq(-4, 4, length.out = 2000)
f_of_e <- plogis(seq(-4, 4, length.out = 2000))
e_of_f1 <- rowMeans(plogis(replicate(5000, seq(-4, 4, length.out = 2000)) + matrix(rnorm(2000*5000, 0, 1), nrow = 2000, ncol = 5000)))
e_of_f2 <- rowMeans(plogis(replicate(5000, seq(-4, 4, length.out = 2000)) + matrix(rnorm(2000*5000, 0, 2), nrow = 2000, ncol = 5000)))
jensen <- data.frame(x = x, f_of_e = f_of_e, e_of_f1 = e_of_f1, e_of_f2 = e_of_f2)
jensen <- melt(jensen, id.vars = "x")
ggplot(jensen, aes(x = x, y = value, color = variable)) + geom_line() + theme_bw() + ylab("") +
xlab("X") +
scale_color_discrete(name = "X := N(0,sigma)",
labels = c("f(E[X])",
"E[f(X)] when sigma = 1",
"E[f(X)] when sigma = 2"))
```
In essence, using $\mu_{\alpha_j}$ or its standardized version will result in more extreme estimates due to the nonlinearity in the transformation. However, obtaining reliable estimates of the probability of support of question $k$ for each poststratification cell $j$ is still possible:
1. Draw with replacement $L$ individuals from the poststratification table (weighting by $N$, the number of people in each cell).
2. Calculate $\mu_{\alpha_l}$ for each subject $l$, and then add some random noise centered at zero and with standard deviation $\sigma_\alpha$ (which was estimated in the model). This simulates the $\alpha_l$ for a random sample of $L$ subjects that come from the population defined by the poststratification table.
3. Given $\alpha_l$, calculate $\bar{\alpha}_l$ and $s_{\alpha_l}$. These values correspond to the estimated average and standard deviation for the abilities in the population defined by the poststratification table.
5. For each poststratification cell $t$:
i. Simulate $s$ draws from the distribution of alphas $\alpha_s \sim \text{normal}(\mu_{\alpha_t}, \sigma_\alpha)$. These $s$ draws correspond to individuals with the demographic-geographic factors defined in cell $t$.
ii. Standardize $\alpha_s^{adj} = \frac{\alpha_s - \bar{\alpha}_l}{s_{\alpha_l}}$
iii. Considering $\alpha_s^{adj}$ is a vector with $s$ elements, obtain $P(y_{k,t} = 1) = \text{Mean}(logit^{-1}(\gamma_k^{adj}\times(\alpha_s^{adj} - \beta_k^{adj})))$
$P(y_{k,t} = 1)$ represents the average support for question $k$ among individuals in cell $t$. To propagate the uncertainty about the parameters in the model, these steps must be repeated once for every posterior draw $d$, obtaining a $D \times T$ matrix that can be poststratified as usual.
### Results from Standard and Ideal Point MRP
We compare the individual-question estimates for the ideal point model and the standard model. As expected, the results from both methods are similar, although there are also some differences.
#### Question 6
> Make abortions illegal in all circumstances
The following code implements the algorithm described above that results in the $D \times T$ matrix $P(y_{k,t} = 1)$. Instead of considering the $D$ posterior draws, we only use 25 for computational efficiency. This $P(y_{k,t} = 1)$ matrix is then poststratified and, ultimately, we obtain the national and state-level estimates.
```{r, fig.height= 3.5, fig.width=12, echo=FALSE, fig.align = "center", warning=FALSE, message=FALSE}
# Standard MRP Results
if(FALSE){
fit_standard6 <- stan_glmer(abortion6 ~ (1 | state) + (1 | age) + (1 | ethnicity) + (1 | educ) + male +
repvote + (1 | region),
family = binomial(link = "logit"),
data = left_join(df, statelevel_predictors),
prior = normal(0, 1, autoscale = TRUE),
prior_covariance = decov(scale = 0.50),
adapt_delta = 0.99,
seed = 1010)
saveRDS(fit_standard6, file = "data_public/chapter3/models/individual/fit_standard6.rds")
} else {
fit_standard6 <- readRDS("data_public/chapter3/models/individual/fit_standard6.rds")
}
P <- posterior_epred(fit_standard6, newdata = left_join(postrat_df, statelevel_predictors))
national_level_standard <- P %*% postrat_df$n / sum(postrat_df$n)
df_state_standard <- data.frame(state = rep(NA, length(levels(df$state))),
state_mean = rep(NA, length(levels(df$state))),
state_sd = rep(NA, length(levels(df$state))))
i = 1
for(s in levels(df$state)){
state_estimates <- (P[, which(postrat_df$state==s)] %*% postrat_df$n[which(postrat_df$state==s)]/
sum(postrat_df$n[which(postrat_df$state==s)]))
df_state_standard$state[i] <- s
df_state_standard$state_mean[i] <- mean(state_estimates)
df_state_standard$state_sd[i] <- sd(state_estimates)
i = i + 1
}
# Ideal Point MRP Results
fit <- readRDS("data_public/chapter3/models/fit_idealpoint.rds")
```