File size: 25,604 Bytes
3af64c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#figure 4: Coethnic voting preferences in candidate conjoint experiment, 
#comparing high- to low-exposure respondents. 
#This also includes candidate-comparison results for Appendix

# install.packages('plyr')
# install.packages('dplyr')
# install.packages('tidyr')
# install.packages('ggplot2')
# install.packages('multiwayvcov')
# install.packages('lmtest')
# install.packages('stargazer')

rm(list=ls())
#setwd() #set working directory
dir.create(paste0(getwd(), '/Output/'))
dir.create(paste0(getwd(), '/Output/Figure_4/'))
path0 = paste0(getwd(), '/Output/Figure_4/', Sys.Date(),'/') #Directory for output files
dir.create(path0)

s = function(x){summary(factor(x))}
Num = function(x){as.numeric(as.factor(x))}

library(plyr);library(dplyr, warn.conflicts = FALSE)
library(tidyr);library(ggplot2)
suppressMessages(library(multiwayvcov, warn.conflicts = F))
suppressMessages(library(lmtest, warn.conflicts = F))
suppressMessages(library(stargazer))

A = readRDS('4-20-20_HH-KNearest_DeID_demed.RDS')

#Data cleaning
Aprime = A[A$A.A7_Area.Neighborhood %in% names(which(table(A$A.A7_Area.Neighborhood) >= 30)),]#DROP PLACES WITH <30 OBSERVATIONS
Aprime = Aprime[which(!is.na(Aprime$A.A7_Area.Neighborhood)),] #drop NA neighborhoods
Aprime = Aprime[which(Aprime$A.A7_Area.Neighborhood != 'Bangalore NA'),]

Q = Aprime

###################################################################################################
#Conjoint analysis
#Rename variables
Q = Q %>% dplyr::rename(Q1A1 = L.Candidate_Random_A1_Candidate.Preferance, #first question, candidate 1, characteristic A
                        Q1A2 = L.Candidate_Random_A2_Candidate.Preferance, #first question, candidate 2, characteristic A
                        Q1B1 = L.Candidate_Random_B1_Candidate.Preferance, #first question, candidate 1, characteristic B
                        Q1B2 = L.Candidate_Random_B2_Candidate.Preferance, #first question, candidate 2, characteristic B
                        Q2A1 = L.Candidate_Random_A3, #second question, candidate 1, characteristic A
                        Q2A2 = L.Candidate_Random_A4, #second question, candidate 2, characteristic A
                        Q2B1 = L.Candidate_Random_B3, #second question, candidate 1, characteristic B
                        Q2B2 = L.Candidate_Random_B4, #second question, candidate 2, characteristic B
                        Q3A1 = L.Candidate_Random_A5, #third question, candidate 1, characteristic A
                        Q3A2 = L.Candidate_Random_A6, #third question, candidate 2, characteristic A
                        Q3B1 = L.Candidate_Random_B5, #third question, candidate 1, characteristic B
                        Q3B2 = L.Candidate_Random_B6, #third question, candidate 2, characteristic B
                        Q1 = L.Candidate_Question_1, #first question, choose candidate 1 or 2
                        Q2 = L.Candidate_Question_2, #first question, choose candidate 1 or 2
                        Q3 = L.Candidate_Question_3 #first question, choose candidate 1 or 2
) 

#rearrange so one row is one conjoint observation. 3x as many rows as A
#new variables: A1, B1 are two traits for candidate 1; similar for 2; and y is responent's choice between candidates
B = Q %>% unite('Q1', matches('Q1')) %>% unite('Q2', matches('Q2')) %>% unite('Q3', matches('Q3')) %>%
  gather(Question, b, starts_with('Q')) %>% arrange(X) %>% separate( 'b', c('A1','A2','B1','B2','y') )

B = B %>% filter(! (A1 == A2 & B1 == B2)) #drop observations where candidates have same profile

#make new data frame wheer each row is one PROFILE, ie each question becomes two rows (one for each candidate)
#New variables: A1, A2 are combined as A: trait A for either candidate
C = B %>% unite('AB1',c(A1,B1)) %>% unite('AB2',c(A2,B2)) %>% gather(Neighbor, AB, c(AB1, AB2)) %>%
  arrange(X) %>% separate('AB', c('A','B')) %>% 
  mutate(Neighbor = as.numeric(mapvalues(Neighbor, from = c('AB1', 'AB2'), to = c(1,2))))

#function to make dummies for trait levels
ModFn = function(x,f){
  data.frame(x, model.matrix(as.formula(f), data=x)) }

C = C %>% ModFn('~ A - 1') %>% ModFn('~ B - 1') #function to make dummies for trait levels
C = C %>% mutate(Y = y == Neighbor) #1 when that candidate is picked
C = C %>% dplyr::rename(A_0 = A0, #rename variables to be consistent with earlier version of code
                        A_1 = A1,
                        A_2 = A2,
                        A_3 = A3,
                        B_0 = B0,
                        B_1 = B1,
                        B_2 = B2,
                        B_3 = B3,
                        B_4 = B4)

B = C; rm(C) #rename
###########################################################################################

###########################################################################################
#Setup for subgroup analysis

#regression formula
form1 = as.formula(paste0('Y ~ ',
                          paste(strsplit('A_0 A_1 A_2 A_3 B_0 B_1 B_2 B_3 B_4',
                                         split = ' ')[[1]], collapse = ' + ' )))

#function to make data frame from regression results
DF_C = function(l_m, id){
  l_m_pl = data.frame(Parameter = rownames(l_m[-1,])) %>% #-1 drops intercept
    mutate(Coef = l_m[-1,1]) %>%
    mutate(Lo = Coef - 1.96 * l_m[-1,2]) %>%
    mutate(Hi = Coef + 1.96 * l_m[-1,2]) %>%
    mutate(ID = id) %>%
    rbind(data.frame(Parameter = c('A_3','B_4'),
                     Coef = c(0,0), Lo = c(0,0), Hi = c(0,0), ID = c(id, id)) ) %>%
    mutate(Parameter = as.character(Parameter)) %>%
    arrange(Parameter)
}
###########################################################################################
 
###########################################################################################
#Make function to extract p- and z-values for each choice of k

calc_p_relig = function(k, Dat){
  var <- paste0('Nearest',k,'_OwnReligion')
  if(median(Dat[,var],na.rm=T)==k){ #split the sample at the median value of KNN (or at K - 1, if the median is K)
    var_break <- k-1
  }else{var_break = floor(median(Dat[,var],na.rm=T))}
  dat_lo = Dat[ which(Dat[,var] <= var_break ) ,] # low knn group
  dat_hi = Dat[ which(Dat[,var] > var_break ) ,]  #high kn group
  if(nrow(dat_lo) == 0 | nrow(dat_hi) == 0){p_a2 = NA #set p-value to NA if there are no respondents in high- or low-exposure group
  }else{
  lm_lo = lm(form1, data = dat_lo ) #run regression on lo-knn group
  lm_hi = lm(form1, data = dat_hi ) #run regression on hi-knn group
  lm_clus_lo = coeftest(lm_lo, cluster.vcov(lm_lo, dat_lo[,c('X','A.A7_Area.Neighborhood')])) #calculate cluster-robust std errors
  lm_clus_hi = coeftest(lm_hi, cluster.vcov(lm_hi, dat_hi[,c('X','A.A7_Area.Neighborhood')])) #calculate cluster-robust std errors
  #z-test for difference in coefficients between lo- and hi-exposure groups
  z_a2 = (lm_clus_lo['A_2','Estimate'] - lm_clus_hi['A_2','Estimate']) / sqrt(lm_clus_lo['A_2','Std. Error']^2 + lm_clus_hi['A_2','Std. Error']^2) 
  #calculate p-value, based on outcome of z-test above
  p_a2 = 2 * pnorm( abs(z_a2), mean = 0, sd = 1, lower.tail = F) 
  coef_lo = lm_clus_lo['A_2','Estimate']; coef_hi = lm_clus_hi['A_2','Estimate'] #extract coefficients for inclusion in output data frame
  sd_lo = lm_clus_lo['A_2','Std. Error']; sd_hi = lm_clus_hi['A_2','Std. Error'] #extract se's for inclusion in output data frame
  #output data frame with coefficients, std errors, and p-value for difference in coefficients between hi- and lo-exposure groups
  return(data.frame(coef_lo, coef_hi, sd_lo, sd_hi, p_a2)) } 
  }

#Calculate results for k in 1:30
relig_results = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B)) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
         )

#Create data frame for plotting
rrc = relig_results[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))

#################################################################
#Figure 4: main result
ggplot(data = rrc, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('k-Nearest Own Religion') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))

ggsave(filename = paste0(path0, 'Fig_4_k-z_coefficients.png'), height = 150, width = 150, units = 'mm')

#################################################################

#################################################################
#Main result in table form
#TABLE A4
relig_results_tab = relig_results %>% apply(2, function(x) as.numeric(x)) %>% data.frame() %>%
  select(k, coef_lo, sd_lo, coef_hi, sd_hi, p_a2) %>% 
  rename(Coef_LowSeg = coef_lo, SD_LowSeg = sd_lo, Coef_HiSeg = coef_hi, SD_HiSeg = sd_hi, p = p_a2) %>% 
  round(3)
out = stargazer(relig_results_tab, summary = F, rownames = F,
                title = 'Results for co-ethnicity attribute in candidate experiment compared between
                high- and low-segregation subsamples, based on religious segregation.',
                label = 'table:ReligResults')
writeLines(out,con = paste0(path0,'ReligResults.tex'));rm(out, relig_results_tab)

#################################################################################################################################################

#################################################################################################################################################
#De-medianed version

zpk_relig = function(data, Split, k){ # nearest k same religion
  var = paste0('Nearest',k,'_OwnReligion')
  VarLo = Split# - 1 
  VarHi = Split# - 1
  lm_lo = lm( form1, data = data[which(data[,var] < VarLo),] ) 
  lm_hi = lm( form1, data = data[which(data[,var] >= VarHi),] )
  lm_lo_sum = coeftest(lm_lo, cluster.vcov(lm_lo, data[which(data[,var] < VarLo),c('X','A.A7_Area.Neighborhood')] ) )
  lm_hi_sum = coeftest(lm_hi, cluster.vcov(lm_hi, data[which(data[,var] >= VarHi),c('X','A.A7_Area.Neighborhood')] ) )
  diff = lm_lo_sum['A_2','Estimate'] - lm_hi_sum['A_2','Estimate']
  z = (lm_lo_sum['A_2','Estimate'] - lm_hi_sum['A_2','Estimate']) / sqrt(lm_lo_sum['A_2','Std. Error']^2 + lm_hi_sum['A_2','Std. Error']^2)
  p = (2*pnorm(abs(z), mean = 0, sd = 1, lower.tail = FALSE))
  return(data.frame(diff = diff,z=z,p=p,split=Split, k = k))
}
zpk_demed_relig = function(data, Split, k){ # 
  var = paste0('DeMedNearest',k,'_OwnReligion')
  VarLo = Split
  VarHi = Split
  lm_lo = lm( form1, data = data[which(data[,var] < VarLo),] ) 
  lm_hi = lm( form1, data = data[which(data[,var] >= VarHi),] ) #
  lm_lo_sum = coeftest(lm_lo, cluster.vcov(lm_lo, data[which(data[,var] < VarLo),c('X','A.A7_Area.Neighborhood')] ) )
  lm_hi_sum = coeftest(lm_hi, cluster.vcov(lm_hi, data[which(data[,var] >= VarHi),c('X','A.A7_Area.Neighborhood')] ) ) #
  diff = lm_lo_sum['A_2','Estimate'] - lm_hi_sum['A_2','Estimate']
  z = (lm_lo_sum['A_2','Estimate'] - lm_hi_sum['A_2','Estimate']) / sqrt(lm_lo_sum['A_2','Std. Error']^2 + lm_hi_sum['A_2','Std. Error']^2)
  p = (2*pnorm(abs(z), mean = 0, sd = 1, lower.tail = FALSE))
  return(data.frame(diff = diff,z=z,p=p,split=Split, k = k))
}

varlist = as.list(seq(5,30,5))
NR_out = ldply(varlist, function(x) zpk_relig(data = B %>% filter(Wave %in% c( 'Bangalore 2016','Jai-Pat 2015') ),
                                              Split = x,
                                              k = as.character(x)) )

NR_out_demed = ldply(varlist, function(x) zpk_demed_relig(data = B %>% filter(Wave %in% c( 'Bangalore 2016','Jai-Pat 2015') ),
                                                          Split = 0,
                                                          k = as.character(x)) )

NR_out$se =  NR_out$diff / NR_out$z
NR_out$lo = NR_out$diff - 1.96*NR_out$se
NR_out$hi = NR_out$diff + 1.96*NR_out$se
NR_out$id = 'k-Nearest Neighbors'

NR_out_demed$se =  NR_out_demed$diff / NR_out_demed$z
NR_out_demed$lo = NR_out_demed$diff - 1.96*NR_out_demed$se
NR_out_demed$hi = NR_out_demed$diff + 1.96*NR_out_demed$se
NR_out_demed$id = 'De-Medianed k-Nearest Neighbors'

out = rbind(NR_out, NR_out_demed)

#FIGURE A4
ggplot(out, group = id, aes(x=k)) +
  geom_point(aes(y = diff, color = id), position=position_dodge( width = 0.5 )) +
  geom_errorbar(aes(ymin = lo, ymax = hi, group = id), position=position_dodge( width = 0.5 )) +
  labs(x = 'k', y = 'Diff. of Coefficients (Lo - Hi Seg)') +
  scale_color_discrete(name='Metric', labels=c('De-Med. K-Nearest', 'K-Nearest')) +
  theme_minimal() + theme(text=element_text(size=16)) + theme(legend.title.align=0.5)
ggsave(filename = paste0(path0, 'demed-k-z-full.png'), height = 150, width = 150, units = 'mm')
#################################################################################################################################################

#################################################################################################################################################
#Plots for non-balanced attributes

relig_results_hin = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$C.C6_Religion == 'Hindu'),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )
rrc_hin = 
  relig_results_hin[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
#FIGURE A6
ggplot(data = rrc_hin, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + #
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Hindu)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_hindu.png'), height = 150, width = 150, units = 'mm')

relig_results_mus = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$C.C6_Religion == 'Muslim'),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )

rrc_mus = 
  relig_results_mus[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
#FIGURE A7
ggplot(data = rrc_mus, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Muslim)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_muslim.png'), height = 150, width = 150, units = 'mm')

relig_results_hiassets = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$AssetSum >= 10),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )

rrc_hiassets = 
  relig_results_hiassets[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
#FIGURE A8
ggplot(data = rrc_hiassets, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Hi Assets)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_hiassets.png'), height = 150, width = 150, units = 'mm')

relig_results_hicaste = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$C.C8_Caste == 'General/BC/OBC'),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )

rrc_hicaste = 
  relig_results_hicaste[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
ggplot(data = rrc_hicaste, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Hi Caste)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_hicaste.png'), height = 150, width = 150, units = 'mm')

relig_results_jaipur = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$City == 'Jaipur'),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )

rrc_jaipur = 
  relig_results_jaipur[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
ggplot(data = rrc_jaipur, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Jaipur)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_jaipur.png'), height = 150, width = 150, units = 'mm')

relig_results_patna = sapply(1:30, function(x) calc_p_relig(k=x, Dat = B[which(B$City == 'Patna'),])) %>% t() %>% data.frame()  %>%
  mutate(k = 1:30,
         dif = as.numeric(coef_lo) - as.numeric(coef_hi),
         dif_sd = sqrt(as.numeric(sd_lo)^2 + as.numeric(sd_hi)^2),
         dif_lobd = dif - 1.96*dif_sd,
         dif_hibd = dif + 1.96*dif_sd
  )

rrc_patna = 
  relig_results_patna[seq(from = 2, to = 30, by = 3),] %>% 
  rename(Low = coef_lo, High = coef_hi) %>%
  select(-starts_with('dif')) %>% 
  gather(Seg, Coef, c(Low, High)) %>% mutate(Coef = as.numeric(Coef),
                                             sd_lo = as.numeric(sd_lo),
                                             sd_hi = as.numeric(sd_hi),
                                             p_a2 = as.numeric(p_a2),
                                             sd = sd_lo*(Seg == 'Low') + sd_hi*(Seg == 'High'),
                                             lo = Coef - 1.96*sd,
                                             hi = Coef + 1.96*sd,
                                             sig = factor(p_a2 < 0.05))
ggplot(data = rrc_patna, aes(x = k, y = Coef)) + 
  geom_pointrange(aes(ymin = lo, ymax = hi, x = k, shape = Seg, alpha = sig), 
                  position = position_dodge(width = 0.9)) +
  scale_shape_manual('Exposure', values = c(16, 17), labels = c('Low','High')) + 
  scale_alpha_manual('p < 0.05', c(TRUE, FALSE), values=c(1, 0.5), labels = c('Yes','No')) +
  labs(shape = 'Exposure') + 
  theme_minimal() + ylab('Coethnicity Coefficients') +
  theme(text = element_text(size = 16),
        plot.title = element_text(hjust = 0.5)) + 
  ggtitle('Nearest-k Own Religion (Patna)') +
  guides(shape = guide_legend(order = 1), 
         alpha = guide_legend(order = 0))
ggsave(filename = paste0(path0, 'k-z_coefficients_patna.png'), height = 150, width = 150, units = 'mm')

############################################################################################