-
Notifications
You must be signed in to change notification settings - Fork 10
/
_MAINCODE.R
313 lines (221 loc) · 7.79 KB
/
_MAINCODE.R
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
###############################################################################
## ##
## Polarization and Secular Trends, Main Code ##
## ##
###############################################################################
## Basic Setup ----------------------------------------------------------------
# clear environment
rm(list=ls())
# specify base directory
wd.base <- "working directory here!"
# specify the number of cores to use in the computation
n.cores <- 6
# set paths
if (!exists('code.path'))
code.path <- paste0(wd.base, 'code/')
if (!exists('raw.data.path'))
raw.data.path <- paste0(wd.base, 'raw_data/')
if (!exists('data.path'))
data.path <- paste0(wd.base, 'data/')
if (!exists('graphics.path'))
graphics.path <- paste0(wd.base, 'plots/')
if (!exists('stan.path'))
stan.path <- paste0(wd.base, 'stan/')
if (!exists('tables.path'))
tables.path <- paste0(wd.base,'tables/')
# create directories
if (!dir.exists(data.path)) {
# directory to store results
message(paste0('Creating Directory ~/data/ into ',
wd.base)
)
dir.create(data.path, recursive=T)
}
if (!dir.exists(graphics.path)) {
# directory to store graphics
message(paste0('Creating Directory ~/plots/ into ',
wd.base)
)
dir.create(graphics.path, recursive=T)
}
if (!dir.exists(stan.path)) {
# directory for STAN results
message(paste0('Creating Directory ~/stan/ into ',
wd.base)
)
dir.create(stan.path, recursive=T)
}
if (!dir.exists(tables.path)) {
# directory for tables
message(paste0('Creating Directory ~/tables/ into ', wd.base))
dir.create(tables.path)
}
## Install Needed Libraries ---------------------------------------------------
# libraries needed for replication
needed.libs <- c('dplyr',
'data.table',
'dtplyr',
'ggplot2',
'rstan',
'loo',
'car',
'survey',
'cowplot',
'xtable',
'gridExtra',
'xlsx',
'doParallel')
# libraries not installed
need.inst <- needed.libs[
!(needed.libs %in% installed.packages()[,'Package'])
]
# install libraries
for (ii in need.inst) {
install.packages(ii, repos='http://cran.rstudio.com')
}
# check whether installation was successful (and load)
check.inst <- sapply(needed.libs,
function(w) {
suppressMessages(require(w, character.only=T))
})
if (sum(check.inst) != length(need.inst) &
sum(check.inst) != length(needed.libs)) {
stop(
paste0('Some packages could not be installed. ',
'This might cause the code to crash. ',
'Try to install the following packages manually :\n\n ',
paste0(names(check.inst[check.inst == F]),
collapse=', ')
)
)
}
## Load Function Definitions and Set Options ----------------------------------
# load functions
source(paste0(code.path, '0.Functions.R'))
# create list of objects NOT to remove during analysis
paths.and.funs <- c(
# paths
grep('\\.path|wd\\.base', ls(), value=T),
# defined functions
fun.names,
# number of cores used in parallel processing
'n.cores',
# this object itself
'paths.and.funs'
)
# set R seed
set.seed(19841987)
# load seeds for STAN
stan.seeds <- fread(paste0(raw.data.path, 'stan.seeds.csv'))
## Hypothetical Graphs --------------------------------------------------------
source(paste0(code.path, '0-1.Illustrations.R'))
# Preparing Data for Analysis ------------------------------------------------
## Prepare NES data
source(paste0(code.path, '1-1.Prep_Data_NES.R'))
### Prepare GSS data
source(paste0(code.path, '1-2.Prep_Data_GSS.R'))
### Generate %lib data and merge
source(paste0(code.path, '1-3.Gen_Lib_Data.R'))
# remove unnecessary objects
rm(list = ls()[ls() %in% paths.and.funs == F])
invisible(gc())
## Plotting Descriptive Trends ------------------------------------------------
source(paste0(code.path, '2.Descriptive_Trends.R'))
# remove unnecessary objects
rm(list = ls()[ls() %in% paths.and.funs == F])
invisible(gc())
## Compile STAN Models and Prepare Data ---------------------------------------
### Compiling STAN models
source(paste0(code.path, '3-1.Compile_STAN.R'))
### Prepare Data
# generate STAN data
long.dat <- readRDS(
paste0(data.path, 'comb.dat.rds')
) %>%
melt(
id.vars = c(
'year',
'i.vars.no',
'i.vars.label',
'i.vars.class',
'data.source'
),
variable.name = 'pid',
value.name = 'pr.agree'
)
# drop aggregate props & missings
long.dat <- long.dat[pid != 'props' & !is.na(pr.agree)]
# scale years (into decades)
long.dat[, c.year := (year - 1994) / 10]
long.dat[, c.year.2 := c.year ^ 2]
long.dat[, c.year.3 := c.year ^ 3]
# dummies for partisan groups
long.dat[, ind := ifelse(pid == 'props.i', 1, 0)]
long.dat[, dem := ifelse(pid == 'props.d', 1, 0)]
# order & save
long.dat <- long.dat[order(i.vars.no, pid)]
saveRDS(long.dat, paste0(data.path, 'long.comb.dat.rds'))
# Fit Models -----------------------------------------------------------------
# set basic STAN parameters
options(mc.cores = n.cores)
n.warmup <- 2000
n.iter <- 3000
n.refresh <- 0
# tuning parameters in the case of divergent transitions
# add iterations (warmup is increased by same number)
add.iter <- 2000
# adapt delta
a.delta <- .99
# initial stepsize
s.size <- .01
# maximum treedepth
m.depth <- 12
## Run STAN
source(paste0(code.path, '3-2.Model_Fitting.R'))
### Check for divergence and refit
for (domain in 1:4) {
source(paste0(code.path, '3-3.Check_Div_&_Refit.R'))
}
# remove unnecessary objects
rm(list = ls()[ls() %in% paths.and.funs == F])
invisible(gc())
### Compare model fit with WAIC and LOO
# number of digits to round up to in tables
dig <- 2
# run code
source(paste0(code.path, '3-4.Model_Comparison.R'))
## Summarize Models -----------------------------------------------------------
# selected models (in order, economic, civil rights, moral, foreign)
s.models <- c('quad.bn', 'cubic.bn', 'cubic.bn', 'linear.bn')
# set digits to be displayed in tables
dig <- 3
# number of draws for posterior predictive checks
n.ppc <- 50
# load reshaped data
long.dat <- readRDS(
paste0(data.path, 'long.comb.dat.rds')
)
# Extract posterior samples & posterior predictive checks
for (domain in 1:4) {
source(paste0(code.path, '4-1.Extract_Samps_&_PPC.R'))
}
# summary tables
source(paste0(code.path, '4-2.Model_Tables.R'))
# plots
source(paste0(code.path, '4-3.Model_Plots.R'))
# remove objects
rm(list = ls()[ls() %in% paths.and.funs == F])
invisible(gc())
## Results for Appendix -------------------------------------------------------
# Analyzing only questions on "absolute" (vs. relative) opinion in the
# economic domain
source(paste0(code.path, '5-1.APP_Econ_Refit.R'))
# Regression models adjusting for population change
source(paste0(code.path, '5-2.APP_Comp_Changes.R'))
rm(list = ls()[ls() %in% paths.and.funs == F])
invisible(gc())
## Numbers Cited in Text ------------------------------------------------------
source(paste0(code.path, '6-1.Nums_in_Text.R'))
## Session Info ---------------------------------------------------------------
sessionInfo()
#### END OF CODE ####