-
Notifications
You must be signed in to change notification settings - Fork 0
/
carolina_cornejo_tfm.Rmd
1473 lines (1189 loc) · 33.5 KB
/
carolina_cornejo_tfm.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "TFM"
author: "Carolina Cornejo Castellano"
date: "`r Sys.Date()`"
output:
pdf_document: default
html_document: default
---
# Libraries
```{r libraries, message=FALSE, warning=FALSE}
libraries <- c(
"tidyverse",
"data.table",
"ggplot2",
"sf",
"sp",
"sfdep",
"spdep",
"xSub",
"raster",
"rgdal",
"mapdata",
"janitor",
"spatialreg",
"mapview",
"webshot",
"caret",
"pscl",
"MASS",
"VGAM",
"lmtest",
"modelsummary",
"huxtable"
)
# install (in case they are not already installed) and load libraries
for (lib in libraries) {
if (!requireNamespace(lib, quietly = TRUE)) {
install.packages(lib)
}
suppressPackageStartupMessages(library(lib, character.only = TRUE))
}
# remove vector and iterator
rm(lib, libraries)
```
# Custom options
```{r deactivate scientific notation}
options(scipen = 999)
```
```{r ggplot theme}
blood <- "#B20000"
theme_terror <- function() {
theme_minimal() +
# background
theme(panel.background = element_rect(fill = "white",
color = NA),
plot.background = element_rect(fill = "#F4F4F4")) +
# margins
# theme(plot.margin = margin(20, 20, 25, 15)) + # trbl
theme(plot.margin =
unit(c(0.5, 0.4, 0.5, 0.65), "cm")) + # trbl
# title and subtitle
theme(plot.title = element_text(color = blood,
size = 13,
face = "bold",
hjust = 0.5,
margin = margin(0,0,5,0))) + # trbl
theme(plot.subtitle = element_text(color = "#282828",
size = 11,
hjust = 0.5,
margin = margin(0,0,15,0))) + # trbl
# axis text
theme(axis.text = element_text(color = "#282828",
size = 10)) +
# axis titles
theme(axis.title = element_text(color = blood,
size = 11)) +
theme(axis.title.x = element_text(margin = margin(5,0,0,0))) + # trbl
theme(axis.title.y = element_text(margin = margin(0,10,0,-5))) + # trbl
# legend
theme(legend.position = "bottom",
legend.title = element_text(size = 10),
legend.background = element_rect(color = "#E0E0E0"),
legend.key = element_rect(color = NA),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(color = "#282828",
size = 9)) +
# facet labels
theme(strip.text = element_text(color = blood,
size = 12,
face = "bold")) +
# grid lines
theme(panel.grid.major = element_line(color = "#E0E0E0",
size = 0.15),
panel.grid.minor = element_blank())
}
```
```{r unzip datasets}
unzip("data/data.zip", exdir = "data/")
unzip("shapefiles/peru.zip", exdir = "shapefiles/")
unzip("shapefiles/priogrid.zip", exdir = "shapefiles/")
```
# Load data
Objects ending with "_full" usually refer to the whole period of time (1980-2021).
Objects ending with "_peak" usually refer to the peak period of violence (1980-2000).
Objects ending with "_trough" usually refer to the trough period of violence (2001-2021).
## Load shapefiles
```{r load peru and grid shapefiles}
sh_grid <-
st_read("shapefiles/priogrid/priogrid_cell.shp")
sh_national_borders <- st_geometry(
st_read("shapefiles/peru/peru.shp"))
st_crs(sh_grid)
st_crs(sh_national_borders)
```
Both are in EPSG:4326. This is going to be the CRS of all spatial objects.
```{r st_intersection}
# execute spatial overlay to keep only grids within Peruvian territory
sh_peru <- st_intersection(
sh_grid,
sh_national_borders)
plot(sh_peru$geometry)
st_crs(sh_peru)
```
```{r}
# plot the grids
map_grids <- mapview(sh_peru,
map.types = "OpenStreetMap",
layer.name = "Grids",
col.regions = "gray",
lwd = 2,
col = blood
)
map_grids
```
```{#r}
mapshot(map_grids,
file = "figs/map_grids.png",
vwidth = 480,
vheight = 510)
```
## Load GTD dataset
```{r df_gtd}
# load both datasets, combine them, and select relevant variables.
df_gtd_full <- rbind(fread("data/gtd_1970_2020.csv"),
fread("data/gtd_ene_jun_2021.csv")) %>%
filter(country == 159, # filter only Peru
iyear >= 1980) %>%
dplyr::select(
eventid,
iyear,
longitude,
latitude,
summary,
attacktype1_txt,
targtype1_txt,
nkill,
weaptype1_txt
)
# delete rows without lot and lat
df_gtd_full <- df_gtd_full[!is.na(df_gtd_full$longitude) &
!is.na(df_gtd_full$latitude),]
# turn GTD into sf object:
df_gtd_full <- st_as_sf(df_gtd_full,
coords = c("longitude", "latitude"),
crs = 4326)
plot(df_gtd_full$geometry)
```
Since the Peru and the attacks data are now loaded, let’s make a quick map.
```{r}
mapview(
sh_peru,
layer.name = "Grids",
col.regions = "gray",
legend = T,
map.types = "OpenStreetMap"
) +
mapview(
df_gtd_full,
col.regions = blood,
cex = "nkill",
legend = T,
layer.name = "Attacks 1980-2021"
)
```
Subset GTD data according to periods:
```{r}
df_gtd_peak <- df_gtd_full %>%
filter(
iyear <= 2000
)
```
```{r}
df_gtd_trough <- df_gtd_full %>%
filter(
iyear >= 2001
)
```
```{r}
df_gtd_full$target_group <- ifelse(
df_gtd_full$targtype1_txt %in% c(
"Business", "Government (General)",
"Private Citizens & Property", "Police"),
df_gtd_full$targtype1_txt, "Others")
df_gtd_full %>%
ggplot(aes(x = target_group,
fill = target_group)) +
geom_bar() +
labs(x = "Targets", y = "Count",
title = "Target types",
subtitle = "1980-2021",
fill = "Targets") +
theme_terror() +
theme(axis.text.x = element_blank()) +
theme(axis.title.x = element_blank()) +
facet_wrap(vars(iyear)) +
scale_fill_manual(values = c("gray50", "red", "gray70", blood, "gray90"))
df_gtd_full$target_group <- NULL
```
```{r}
df_gtd_full$attack_type_group <- ifelse(
df_gtd_full$attacktype1_txt %in% c(
"Bombing/Explosion", "Armed Assault",
"Assassination", "Facility/Infrastructure Attack"),
df_gtd_full$attacktype1_txt, "Others")
df_gtd_full %>%
ggplot(aes(x = attack_type_group,
fill = attack_type_group)) +
geom_bar() +
labs(y = "Count",
title = "Attack types",
subtitle = "1980-2021",
fill = "Attack types") +
theme_terror() +
theme(axis.text.x = element_blank()) +
theme(axis.title.x = element_blank()) +
facet_wrap(vars(iyear)) +
scale_fill_manual(values = c("gray50", "red", "gray70", blood, "gray90"))
df_gtd_full$attack_type_group <- NULL
```
```{r}
df_gtd_full$weapon_group <- ifelse(
df_gtd_full$weaptype1_txt %in% c(
"Explosives", "Firearms",
"Incendiary", "Melee"),
df_gtd_full$weaptype1_txt, "Others")
df_gtd_full %>%
ggplot(aes(x = weapon_group,
fill = weapon_group)) +
geom_bar() +
labs(y = "Count",
title = "Weapon types",
subtitle = "1980-2021",
fill = "Weapons") +
theme_terror() +
theme(axis.text.x = element_blank()) +
theme(axis.title.x = element_blank()) +
facet_wrap(vars(iyear)) +
scale_fill_manual(values = c("gray50", "red", "gray70", blood, "gray90"))
df_gtd_full$weapon_group <- NULL
```
## Load PRIO dataset
Variables: https://grid.prio.org/#/download
The variable `drug_y` had many NAs, which later greatly affected the execution of the algorithms. The data source provides information on cannabis, coca and opium cultivation worldwide, although only coca cultivation corresponds to Peruvian territory. By mapping this information and contrasting it with other sources of information, I concluded that it was not the case that there was no information on the other grids, but that in fact drugs are not grown in them. Therefore, and only after reaching this conclusion, I proceeded to replace the NA with 0.
I could not reach to the same conclusion regarding the `excluded` variable, which also had NAs.
Although they may seem static, there are some variables that do change over the years, which is why I chose to use the average for each period.
```{r prio whole period dataset}
df_prio <- read_csv("data/prio.csv")
df_prio$drug_y[is.na(df_prio$drug_y)] <- 0
df_prio_full <- df_prio %>%
group_by(gid) %>%
summarize(
bdist3 = mean(bdist3,
na.rm = TRUE
),
capdist = mean(capdist,
na.rm = TRUE
),
drug_y = mean(drug_y,
na.rm = TRUE
),
excluded = mean(excluded,
na.rm = TRUE
)
)
# Turn all NaN into NA
df_prio_full <- df_prio_full %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
```{r prio peak dataset}
df_prio_peak <- df_prio %>%
group_by(gid) %>%
summarize(
bdist3 = mean(
ifelse(year <= 2000, bdist3, NA),
na.rm = TRUE
),
capdist = mean(
ifelse(year <= 2000, capdist, NA),
na.rm = TRUE
),
drug_y = mean(
ifelse(year <= 2000, drug_y, NA),
na.rm = TRUE
),
excluded = mean(
ifelse(year <= 2000, excluded, NA),
na.rm = TRUE
)
)
# turn all NaN into NA
df_prio_peak <- df_prio_peak %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
```{r prio trough dataset}
df_prio_trough <- df_prio %>%
group_by(gid) %>%
summarize(
bdist3 = mean(
ifelse(year >= 2001, bdist3, NA),
na.rm = TRUE
),
capdist = mean(
ifelse(year >= 2001, capdist, NA),
na.rm = TRUE
),
drug_y = mean(
ifelse(year >= 2001, drug_y, NA),
na.rm = TRUE
),
excluded = mean(
ifelse(year >= 2001, excluded, NA),
na.rm = TRUE
)
)
# turn all NaN into NA
df_prio_trough <- df_prio_trough %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
## Load xSub dataset
Variables: https://cross-sub.org/about/variables-included
```{#r download xSub dataset}
get_xSub(data_source = "GED",
country_iso3 = "PER", # only info for Peru
space_unit = "priogrid",
time_unit = "year",
out_dir = "data/")
```
```{r xsub whole period dataset}
df_xsub <- read_csv("data/xSub_GED_PER_priogrid_year.csv") %>%
dplyr::select(
PRIO_GID,
YEAR,
ELEV_MEAN,
OPEN_TERRAIN,
WLMS_NLANG
)
# variables to lower case
df_xsub <- clean_names(df_xsub)
# rename prio_gid to only "gid"
names(df_xsub)[1] <- "gid"
df_xsub_full <- df_xsub %>%
group_by(gid) %>%
summarize(
elev_mean = mean(
elev_mean,
na.rm = TRUE),
open_terrain = mean(
open_terrain,
na.rm = TRUE),
wlms_nlang = mean(
wlms_nlang,
na.rm = TRUE)
)
# turn all NaN into NA
df_xsub_full <- df_xsub_full %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
```{r xsub peak dataset}
df_xsub_peak <- df_xsub %>%
group_by(gid) %>%
summarize(
elev_mean = mean(
ifelse(year <= 2000, elev_mean, NA),
na.rm = TRUE),
open_terrain = mean(
ifelse(year <= 2000, open_terrain, NA),
na.rm = TRUE),
wlms_nlang = mean(
ifelse(year <= 2000, wlms_nlang, NA),
na.rm = TRUE)
)
# turn all NaN into NA
df_xsub_peak <- df_xsub_peak %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
```{r xsub trough dataset}
df_xsub_trough <- df_xsub %>%
group_by(gid) %>%
summarize(
elev_mean = mean(
ifelse(year >= 2001, elev_mean, NA),
na.rm = TRUE),
open_terrain = mean(
ifelse(year >= 2001, open_terrain, NA),
na.rm = TRUE),
wlms_nlang = mean(
ifelse(year >= 2001, wlms_nlang, NA),
na.rm = TRUE)
)
# turn all NaN into NA
df_xsub_trough <- df_xsub_trough %>%
mutate_all(~ifelse(is.nan(.),
NA, .))
```
So far, `df_prio_*` datasets have information of all the grids in the world, and `df_gtd_*` and `df_xsub_*` have information only of the grids within the Peruvian territory.
## Introductory overview of the attacks
Before doing more transformations on the data, lets visualize the 3 time ranges:
```{r mapview 1980 - 2021}
map_full <- mapview(
sh_peru,
layer.name = "Grids",
col.regions = "gray",
legend = T,
map.types = "OpenStreetMap"
) +
mapview(
df_gtd_full,
col.regions = blood,
cex = "nkill",
legend = T,
layer.name = "Attacks 1980-2021"
)
map_full
```
```{r mapview 1980 - 2000}
map_peak <- mapview(
sh_peru,
layer.name = "Grids",
col.regions = "gray",
legend = T,
map.types = "OpenStreetMap"
) +
mapview(
df_gtd_peak,
col.regions = blood,
cex = "nkill",
legend = T,
layer.name = "Attacks 1980-2000"
)
map_peak
```
```{r mapview 2001 - 2021}
map_trough <- mapview(
sh_peru,
layer.name = "Grids",
col.regions = "gray",
legend = T,
map.types = "OpenStreetMap"
) +
mapview(
df_gtd_trough,
col.regions = blood,
cex = "nkill",
legend = T,
layer.name = "Attacks 2001-2021"
)
map_trough
```
```{#r save mapview plots}
# to save these mapview as pngs
# webshot::install_phantomjs() # needs to be installed only once
mapshot(map_full,
file = "figs/map_full.png",
vwidth = 480,
vheight = 510)
mapshot(map_peak,
file = "figs/map_peak.png",
vwidth = 480,
vheight = 510)
mapshot(map_trough,
file = "figs/map_trough.png",
vwidth = 480,
vheight = 510)
```
## Create joint datasets
### Whole period
```{r joins}
# subset grid variables within Peru's borders
sh_1 <- dplyr::left_join(sh_peru,
df_prio_full,
by = "gid"
)
# merge with xSub Peru's data
sh_attrs_full <- dplyr::left_join(sh_1,
df_xsub_full,
by = "gid"
)
names(sh_attrs_full)
```
The following process is replicated as seen in Walker (2023) and Kaplan (2022). It is needed to get a count of the attacks per grid. The `st_join()` function matches each attack to its corresponding grid. Here, the order of arguments is important: the attacks data is used first to aggregate at the attack level.
```{r points-in-polygon join}
attacks_agg_full <- st_join(
df_gtd_full,
sh_attrs_full
)
```
There is no variable available with the number of attacks, so it needs to be created. The variable "number_attacks" is assigned a value of 1 since each row represents only one attack.
```{r}
attacks_agg_full$number_attacks <- 1
```
Now it is possible to aggregate the data and assign the results back into `attacks_agg_full`.
```{r attacks aggregation}
# this should substantially trim rows, dropping grid cells lacking attack data
attacks_agg_full <- attacks_agg_full %>%
group_by(gid) %>%
summarize(number_attacks = sum(number_attacks))
```
It is needed to keep all rows in `sh_attrs_full` (keep all grids) to use `left_join(sh_attrs_full, attacks_agg_full)`. I assigned the results to a new data set called `sf_attrs_attacks`. The geometry column for `attacks_agg_full` will not be useful anymore, and it will cause problems with the join if kept.
```{r delete geometry in attacks_agg}
attacks_agg_full$geometry <- NULL
```
Now it is possible to do the join. Since this will be the data frame in use from now on, it will be given a shorter name: `df_full`.
```{r}
df_full <- left_join(sh_attrs_full,
attacks_agg_full,
by = "gid")
# replace NAs with 0, because those are grids without attacks
df_full$number_attacks[ is.na(df_full$number_attacks) ] <- 0
```
```{r}
ggplot(df_full, aes(x = number_attacks)) +
geom_histogram(bins = 30,
fill = blood,
color = "black") +
theme_terror() +
labs(title = "Terrorist attacks in Peru",
subtitle = "1980 - 2021",
x = "Number of attacks",
y = "Number of grids")
```
### Peak period
Same process as before.
```{r}
# subset grid variables within Peru's borders
sh_1 <- dplyr::left_join(sh_peru,
df_prio_peak,
by = "gid"
)
# merge with xSub Peru's data
sh_attrs_peak <- dplyr::left_join(sh_1,
df_xsub_peak,
by = "gid"
)
attacks_agg_peak <- st_join(
df_gtd_peak,
sh_attrs_peak
)
attacks_agg_peak$number_attacks <- 1
attacks_agg_peak <- attacks_agg_peak %>%
group_by(gid) %>%
summarize(number_attacks = sum(number_attacks))
attacks_agg_peak$geometry <- NULL
df_peak <- left_join(sh_attrs_peak,
attacks_agg_peak,
by = "gid")
# replace NAs with 0
df_peak$number_attacks[ is.na(df_peak$number_attacks) ] <- 0
```
```{r}
ggplot(df_peak, aes(x = number_attacks)) +
geom_histogram(bins = 30,
fill = blood,
color = "black") +
theme_terror() +
labs(title = "Terrorist attacks in Peru",
subtitle = "1980 - 2000",
x = "Number of attacks",
y = "Number of grids")
```
### Trough period
Same process.
```{r}
# subset grid variables within Peru's borders
sh_1 <- dplyr::left_join(sh_peru,
df_prio_trough,
by = "gid"
)
# merge with xSub Peru's data
sh_attrs_trough <- dplyr::left_join(sh_1,
df_xsub_trough,
by = "gid"
)
# create temporal df to aggregate attacks numbers
attacks_agg_trough <- st_join(
df_gtd_trough,
sh_attrs_trough
)
attacks_agg_trough$number_attacks <- 1
# aggregate attacks
attacks_agg_trough <- attacks_agg_trough %>%
group_by(gid) %>%
summarize(number_attacks = sum(number_attacks))
attacks_agg_trough$geometry <- NULL
df_trough <- left_join(sh_attrs_trough,
attacks_agg_trough,
by = "gid")
# replace NAs with 0
df_trough$number_attacks[ is.na(df_trough$number_attacks) ] <- 0
```
```{r}
ggplot(df_trough, aes(x = number_attacks)) +
geom_histogram(bins = 30,
fill = blood,
color = "black") +
theme_terror() +
labs(title = "Terrorist attacks in Peru",
subtitle = "2001 - 2021",
x = "Number of attacks",
y = "Number of grids")
```
```{r declutter environment}
rm(list = setdiff(ls(), c(
"df_full", "df_peak", "df_trough", # master datasets
"theme_terror", "blood", # ggplot theme and custom color
"sh_grid", "sh_national_borders",
"map_full", "map_peak", "map_trough")
)
)
gc() # free memory
```
# Neighborhoods
The process of creating neighborhoods and weights will only be needed once, regardless of the period, so the data frame for the whole period will be used. `queen = TRUE` means that regions are considered neighbors if they share a common boundary point or corner.
```{r neighborhoods}
nb <- poly2nb(df_full,
queen = TRUE)
summary(nb)
```
This shows that:
- On average, the grids in Peru have 7.03 neighbors,
- there is 1 no-neighbor observation,
- there are 6 least connected regions with only one link each; and
- there are 357 most connected regions, with 8 links each.
The fact that there are 1 no-neighbor observation can be problematic. Keeping the no-neighbor grid raises questions about the relevant size of n when testing for autocorrelation, among other issues. (Bivand, 2013). It was checked internally that in the three data frames it appears that the row with no-neighbors is 191.
```{r}
# delete row with no neighbors
df_full <- df_full[-191,]
df_peak <- df_peak[-191,]
df_trough <- df_trough[-191,]
# compute neighbors again
nb <- poly2nb(df_full,
queen = TRUE)
summary(nb)
```
These new neighbors show that:
- On average, the grids in Peru have 7.04 neighbors; and
- there is no no-neighbor observation
Neighborhood relationships can be visualized with red lines connecting each polygon with its neighbors:
```{r}
plot(df_full$geometry)
plot(nb,
coords = st_coordinates(st_centroid(df_full)),
add = TRUE,
col = blood,
points = FALSE)
```
```{r}
# see row indices of some random neighbors, as examples
nb[[1]]
nb[[255]]
nb[[510]]
```
# Weights
```{r weights for whole period}
lw <- nb2listw(nb,
style = "W")
lw
```
`style = "W"` makes the weights for each polygon standardised to sum to unity. This is also called _row standardisation_.
```{r}
lw$weights[[1]]
lw$weights[[255]]
lw$weights[[510]]
```
For example:
- Given that the grid at row index 1 has 1 neighbor, it is assigned the weight 1.
- Given that the grid at row index 255 has 8 neighbors, each is assigned the weight 0.125.
- Given that the grid at row index 510 has 3 neighbors, each is assigned the weight 0.3333333.
# 1980 - 2000 (peak period)
## Moran's test
```{r}
moran_peak <- moran.test(
df_peak$number_attacks,
listw = lw)
moran_peak
```
The result of Moran’s I test shows that "there is a slight positive correlation relationship, versus an expectation of a slight negative relationship" (as interpreted by Urdinez & Cruz, 2020, in a similar case). The very small p-value indicates that these results are statistically significant.
So, it can be said that the number of attacks show certain spatial autocorrelation when analyzing the data at the grid level (paraphrasing Urdinez & Cruz, 2020).
```{r}
moran.plot(df_peak$number_attacks,
listw = lw,
xlab = "Number of attacks",
ylab = "Number of attacks (spatially lagged)")
```
## SEM - Spatial Error Model
```{r}
# formula for all models
formula <- formula(paste0(
"number_attacks ~
bdist3 +
capdist +
drug_y +
excluded +
elev_mean +
open_terrain +
wlms_nlang"
))
```
```{r}
sem_peak <- spatialreg::errorsarlm(
formula = formula,
data = df_peak,
listw = lw,
na.action = na.omit,
zero.policy = T)
summary(sem_peak)
```
## SAR - Spatial Autoregressive Model
```{r}
sar_peak <- lagsarlm(
formula = formula,
data = df_peak,
listw = lw,
na.action = na.omit,
zero.policy = TRUE)
summary(sar_peak)
```
## LM - Linear model
```{r}
lm_peak <- lm(
formula = formula,
data = df_peak
)
summary(lm_peak)
```
## NB - Negative Binomial regression
```{r message=FALSE, warning=FALSE}
negbin_peak <- glm.nb(
formula = formula,
data = df_peak,
init.theta = 0.2319233539,
na.action = na.omit)
summary(negbin_peak)
```
## ZIP Zero-inflated Poisson models
Would a Poisson be suitable? Poisson regression assumes constant mean and variance.
```{r}
mean(df_peak$number_attacks)
var(df_peak$number_attacks)
print(paste0(length(which(df_peak$number_attacks == 0)),
" out of ",
nrow(df_full),
" grids had 0 attacks."))
```
```{r}
ggplot(df_peak, aes(x = number_attacks)) +
geom_histogram(bins = 30,
fill = blood,
color = "black") +
theme_terror() +
labs(title = "Attacks by grid",
subtitle = "1980 - 2000",
x = "Number of attacks",
y = "Number of grids")
# ggsave("figs/zero_grids.png")
```
```{r}
# this assumes the factors influencing the mean count and the excess zeros are the same
zeroinf_1_peak <- zeroinfl(
formula = number_attacks ~
bdist3 + ## predictors for the Poisson process
capdist +
drug_y +
excluded +
elev_mean +
open_terrain +
wlms_nlang |
bdist3 + ## predictors for the Bernoulli process
capdist +
drug_y +
excluded +
elev_mean +
open_terrain +
wlms_nlang,
data = df_peak,
dist = "poisson",
link = "logit",
na.action = na.omit
)
summary(zeroinf_1_peak)
```
```{r}
# this assumes different factors influence the mean count vs. the probability of having a zero
zeroinf_2_peak <- zeroinfl(
formula = number_attacks ~
bdist3 +
capdist +
drug_y +
excluded +