-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chief_Judges_Work.Rmd
1819 lines (1190 loc) · 56.6 KB
/
Chief_Judges_Work.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: "Chief_Judges_Work"
author: "Urban Labs"
date: "February 26th, 2018"
output: html_document
---
<!---
The data are at case level with CRCASEN being the unique identifier.
03/14 Add plots with incarceration in colors
03/15 Plot of pretrial length and sentence length, grouped / color by defendants released or detained.
03/19 For the second analysis check mid dates for offense pre-trial
03/19 Test including/Excluding concurrent cases
03/23 Arrest History information:
Count of Prior Arrests -
Violent gun charge- Primary contains Weapons Secondary contains hand gun, firearms
Non Violent Arrests -
Gun Charges NV- Primary contains Weapons Seconday contains UUW
Non gun Charges -
--->
```{r}
getwd()
```
```{r load-Libraries}
library(haven)
library(dplyr)
library(plyr)
library(labelled)
library(ggplot2)
library(dict)
library(lubridate)
library(reshape)
library(sqldf)
library(forcats)
library(scales)
library(DescTools)
library(glmmML)
library(fitdistrplus)
library(wesanderson)
library(stargazer)
library(plm)
library(arm)
library(dotwhisker)
library(car)
library(descr)
library(gmodels)
library(olsrr)
library(zoo)
library(effects)
library(sjPlot)
library(texreg)
library(xtable)
```
```{r read}
# Read SPSS data
#felonyData <- read_sav("/export/researchdata/courtdata/pretrial_detention/06 02 Final Crim File.sav")
#muniData <- read_sav("/export/researchdata/courtdata/pretrial_detention/06 01 Final Muni File.sav")
#felonyArrest <- read_sav("/export/researchdata/courtdata/pretrial_detention/gunfiles/06 02 Final Crim File Arrest.sav")
#str(gunFelonyData)
```
```{r}
#saveRDS(felonyData, file="06 02 Final Crime File.rds")
#saveRDS(felonyArrest, file = "06 02 Final Crime File Arrest.rds")
felonyData <- readRDS("/export/projects/courtdata/CJO Pre-Trial Detention/analysis/KSanalysis/Code/06 02 Final Crime File.rds")
felonyArrest <- readRDS("/export/projects/courtdata/CJO Pre-Trial Detention/analysis/KSanalysis/Code/06 02 Final Crime File Arrest.rds")
```
```{r label}
# Assign labels to columns
felonyData <- felonyData %>% set_variable_labels(CRCASEN = "Unique Case Identifier",
CRIRNBR = "IR #",
missIR = "Missing IR# Flag")
```
```{r felonyFilter}
# Subset data to include only felonies, run attributes(felonyDataSubset$ChargeClass) for labels
felonyDataSubset <- subset(felonyData, ChargeClass %in% c('1','2','3','4','5','6','7'))
# Factorize charge descriptions
felonyDataSubset$CLCHGDES <- as.factor(felonyDataSubset$CLCHGDES)
felonyDataSubset$CLAOIC <- as.factor(felonyDataSubset$CLAOIC)
str(felonyDataSubset[,1:32])
```
**The data is for cases disposed in the adult criminal felony court from 2012 through October 2017.**
```{r NewColumns-Arrest-and-District}
felonyDataSubset <- merge(x = felonyDataSubset, y = felonyArrest[, c("CRCASEN","DISTRICT","CRARRDTE")], by = "CRCASEN", all.x = TRUE)
#felonyDataSubset <- subset(felonyDataSubset, DISTRICT == 1)
#felonyDataSubset <- subset(felonyDataSubset, select = c(1:32,747:748,33:746))
```
```{r plotClass}
# Distribution of cases by class of offense
pc <- ggplot(felonyDataSubset, aes(factor(CLCHRCLS))) +
geom_bar(stat = "count") +
xlab("Offense Class")
pc
```
```{r unique}
sapply(felonyDataSubset[,1:34], function(x) length(unique(x)))
```
```{r missing}
# Missing values in data frame
missing <- colSums(sapply(felonyDataSubset[,1:34], is.na))
missing
```
```{r subsetOutliers}
# Remove observation with OutCOmeDt == NA
felonyDataSubset <- felonyDataSubset[!is.na(felonyDataSubset$OutComeDt),]
felonyDataSubset <- subset(felonyDataSubset, format.Date(CRFRSTDT, "%Y") > 2007)
```
```{r felonyCasesUniverse}
# felony cases by year
felonyCasesYear <- as.data.frame(count(felonyDataSubset, year(OutComeDt)))
felonyCasesYear
```
**There are two main primary tasks we're interested in:**
1. First and foremost, our focus in on gun violence in Chicago area. Filter out, all non-gun crimes.
2. Find the # of defendants with multiple cases open against them.
```{r Readtxt}
gunString <- readLines("gun codes string analysis ks.txt")
```
```{r regex}
library(stringr)
# Subset text file to include only charge descriptions
GunChargeDesc <- gunString[12:218]
# Create an empty list to store gun charge descriptions
gunCodes <- vector("list")
# For Loop to iterate over the file and extract all gun charge descriptions
# regex metacharacters descriptions:
# ^ - start of the string
# . - matches any single character
# * - matches at least 0 times
# ref: http://stat545.com/block022_regular-expression.html
for(i in 1:length(GunChargeDesc)){
temp <- gsub("^.*,", "", GunChargeDesc[i])
temp <- gsub("[')>0.]","", temp)
gunCodes <- append(gunCodes, temp)
}
# Subset text file to include only charge sections or statute codes
GunChargeSec <- gunString[219:292]
# Create an empty list to store gun charge sections
gunChargeSec <- vector("list")
for(i in 1:length(GunChargeSec)){
temp <- gsub("^.*,", "", GunChargeSec[i])
temp <- gsub(")>0.","", temp, fixed = TRUE)
temp <- gsub("'","", temp)
gunChargeSec <- append(gunChargeSec, temp)
}
#Write gun charge description to a csv file
#write.table(gunCodes, file = "gunCodes.csv", col.names = NA, row.names = TRUE, sep = "\t")
```
```{r gunFelonies}
# Assign a flag for gun cases based on gun charge descriptions in gunCodes list
felonyDataSubset$GunCase <- as.numeric(toupper(felonyDataSubset$CLCHGDES) %in% gunCodes)
#toupper(felonyDataSubset$CLCHGSEC) %in% gunChargeSec)
# Rearrange
#felonyDataSubset <- subset(felonyDataSubset, select = c(1:34,749,35:748))
# Gun Felonies
gunFelonyData <- subset(felonyDataSubset, GunCase == 1)
```
Based on the matches from String Analysis file provided, 11,404 cases are gun felonies from our original felony caseload of 88,784 which is ~13% of total cases.
```{r AOICs}
# Create a list of all AOIC codes from Gun Felony and match to the broader felony dataset
gunAOIC <- list()
gunAOIC <- unique(gunFelonyData$CLAOIC)
gunAOIC <- gunAOIC[!gunAOIC %in% c("0","9999999")]
felonyDataSubset$GunCase <- as.numeric(toupper(felonyDataSubset$CLCHGDES) %in% unique(gunCodes) |
felonyDataSubset$CLAOIC %in% unique(gunAOIC))
#toupper(felonyDataSubset$CLCHGSEC) %in% unique(gunChargeSec) |
# Rearrange
#felonyDataSubset <- subset(felonyDataSubset, select = c(1:35,749,36:748))
# Gun Felonies
gunFelonyData <- subset(felonyDataSubset, GunCase == 1)
```
```{r gunCasesUniverse}
# gun felony cases by year
gunCasesYear <- as.data.frame(count(gunFelonyData, year(OutComeDt)))
gunCasesYear
#stargazer(gunCasesYear)
```
```{r ageBoxplot}
#ageBox <- ggplot(gunFelonyData, aes(x= "", y= Defendant_Age)) +
# geom_boxplot() +
# xlab("Age") +
# ylab("Distribution of Defendant Age") +
# ylim(0,75) +
#ageBox
```
```{r plotAOIC}
# Gun cases AOIC codes distribution
pc <- ggplot(gunFelonyData, aes(fct_infreq(factor(CLAOIC)))) +
geom_bar(stat = "count") +
xlab("Gun Cases : AOIC codes") +
theme(axis.text.x = element_text(angle = 90, size = 8, hjust = 1))
pc
```
12309 - FELON POSS / USE FIREARMS
12474 - AGG UUW
13855 - ARMED HABITUAL CRIME
12366 - ARMED ROBBERY/ARMED W FIREARM
17785 - AGG UUW/LOADED/NO FCCA
The final tally of gun cases identified is 19,501 cases (13% of total cases). The identification was conducted based on Charge descriptions & AOIC codes.
```{r nonGunChargeDes}
# Non-Gun Charge descriptions
nonGunChargeDes <- list()
nonGunChargeDes <- felonyDataSubset$CLCHGDES[!toupper(felonyDataSubset$CLCHGDES) %in%
unique(toupper(gunFelonyData$CLCHGDES))]
write.table(nonGunChargeDes, file = "nonGunChargeDes.csv", col.names = NA, sep = "\t")
```
Dealing with constructed release indicator variable
```{r plotRelease}
p4 <- ggplot(gunFelonyData, aes(factor(gunFelonyData$Release))) +
geom_bar(stat = "count") +
scale_x_discrete(breaks=c("0","1","2"),
labels=c("Detained",
"Released (I-Bond or EM)",
"Released (D-Bond or C-Bond)")) +
xlab("Release")
p4
```
```{r plotOutCome}
p4 <- ggplot(gunFelonyData, aes(factor(gunFelonyData$OutComeRed))) +
geom_bar(stat = "count") +
scale_x_discrete(breaks=c("1","2","3","4"),
labels=c("Drop",
"Not Guilty",
"Guilty-Pre-Sentence",
"Guilty-Sentence")) +
xlab("Case Outcome")
p4
```
```{r plotJBP}
p4 <- ggplot(gunFelonyData, aes(factor(gunFelonyData$JBP))) +
geom_bar(stat = "count") +
scale_x_discrete(breaks=c("-1","0","1","2","3"),
labels=c("Unknown",
"Case Dropped",
"Jury Trial",
"Bench Trial",
"Plea of Guilty")) +
xlab("JBP")
p4
```
```{r plotJBP1}
p4 <- ggplot(gunFelonyData, aes(factor(year(gunFelonyData$CRFRSTDT)), fill = factor(gunFelonyData$JBP))) +
geom_bar(stat = "count", position = "fill") +
xlab("Case Initiation Year") +
ylab("Percent") +
ggtitle("Percentage Distribution of Case Adjudication Type by Year") +
scale_y_continuous(labels = percent_format()) +
scale_fill_discrete(name = "Type",
breaks = c("-1","0","1","2","3"),
labels = c("Unknown","Case Dropped","Jury Trial","Bench Trial","Plea of Guilty"))
p4
```
### Identifying defendants that had multiple cases open/pending against them:
Below is the outline for the tasks:
1. In order to uniquely identify each defendant, we will use IR# as id.
2. Now, for the part where we need to find defendants that had multiple cases pending against them, we will use CRFRSTDT and OutcomeDT fields.
```{r MissIRpct}
# Percentage of missing Flag
pct <- paste(round(nrow(subset(gunFelonyData, missIR == 1)) / nrow(gunFelonyData),3), "%", sep = "")
pct
```
Given that a very few # of cases are missing IR#, in this case we might be able to use IR# to uniquely identify defendants.
```{r Multiple}
# Filter our cases with non existent or missing IR#
gunFelonyDataIR <- subset(gunFelonyData, missIR == 0)
# Duplicate IRs for identifying defendants with multiple open cases
DuplicateIRs <- gunFelonyDataIR[duplicated(gunFelonyDataIR$CRIRNBR),]
# Create a flag to mark cases with duplicate defendants
gunFelonyData$DuplicateFlag <- as.numeric(gunFelonyData$CRIRNBR %in%
unique(DuplicateIRs$CRIRNBR))
#gunFelonyData <- subset(gunFelonyData, select = c(1:35,749,36:748))
```
```{r Dict}
# Iterate over IR # of each defendant with multiple cases open against them
defendants <- unique(DuplicateIRs$CRIRNBR)
# Create a dict object to store case #, CRFRSTDT and OutCome Date
mdict <- dict()
for(d in 1:length(defendants)){
df <- subset(gunFelonyData[,c("CRCASEN","CRIRNBR","CRFRSTDT","OutComeDt")],
CRIRNBR == as.character(defendants[d]))
mdict[[ defendants[d] ]] <- list(CaseNo=df$CRCASEN,
DocketDate=df$CRFRSTDT,
OutcomeDate=df$OutComeDt)
}
#ConcurrentEdgeCase <- subset(DuplicateIRs, CRIRNBR == "0867962")
#write.table(ConcurrentEdgeCase, file = "ConcurrentEdgeCase.csv", col.names = NA, sep = "\t")
```
```{r Overlap}
# Create a list to store IR#s with overlapping cases
Overlap <- list()
No_Overlap <- list()
OverlapFinal <- list()
# For-Loop to identify IR#s with overlapping cases
for(d in 1:length(defendants)){
DocketDates <- mdict$get(defendants[d])$DocketDate
OutComeDates <- mdict$get(defendants[d])$OutcomeDate
Cases <- mdict$get(defendants[d])$CaseNo
if(length(DocketDates)==length(OutComeDates)){
for(i in 1:length(DocketDates)){
DocketDateInt <- as.Date(DocketDates[i])
OutComeDateInt <- as.Date(OutComeDates[i])
# Remove the current element from list
DocketDates1 <- DocketDates[-i]
Cases1 <- Cases[-i]
counter = 1
len = length(DocketDates1)
repeat {
for(j in 1:length(DocketDates1)){
if(dplyr::between(ymd(DocketDates1[j]), ymd(DocketDateInt), ymd(OutComeDateInt))){
Overlap[[ defendants[d] ]] <- c(Cases[i], Cases1[j])
} else {
No_Overlap[[ defendants[d] ]] <- c(Cases[i], Cases1[j])
}
OverlapFinal[[ defendants[d] ]] <- append(OverlapFinal[[ defendants[d] ]],
Overlap[[ defendants[d] ]])
counter = counter + 1
}
if(counter > len){
break
}
}
}
}
}
```
Now, that we have a list of defendants (IR#s) that have multiple cases pending, we need to determine those defendants that were released or detained pre-trial in any or all of the cases against them.
```{r Overlap1}
# Construct a pre-trial detained or release indicator based on the concurrent cases pending
# Create a look up table with IR#s with concurrent pending cases and pre-trial release and detained flag
# For loop to create a list of all overlapping cases
overlapping_cases <- list()
for(c in 1:length(OverlapFinal)){
temp <- OverlapFinal[[c]]
overlapping_cases <- append(overlapping_cases, temp)
}
gunFelonyData$Overlap <- as.numeric(gunFelonyData$CRCASEN %in% overlapping_cases)
gunFelonyData$Overlap <- as.factor(gunFelonyData$Overlap)
#gunFelonyData <- subset(gunFelonyData, select = c(1:36,750,37:749))
```
```{r ConcConf}
# Subset the dataframe to include identified concurrent cases
gunFelonyData_Conc <- subset(gunFelonyData, Overlap == 1)
defendants_concurrent <- unique(gunFelonyData_Conc$CRIRNBR)
defConcRel <- dict()
DefendantsConcurrentDetained <- list()
DefendantsConcurrentReleased <- list()
# For-Loop to create a list to identify defendants with conflicting release indicators
for(d in 1:length(defendants_concurrent)){
gunFelonyData_dc <- subset(gunFelonyData_Conc, CRIRNBR == defendants_concurrent[d])
defConcRel[[ defendants_concurrent[d] ]] <- list(ReleaseIndicator = gunFelonyData_dc$Release)
for(r in 1:length(defConcRel$get(defendants_concurrent[d])$ReleaseIndicator)){
if(defConcRel$get(defendants_concurrent[d])$ReleaseIndicator[r] == 0){
temp <- defendants_concurrent[d]
DefendantsConcurrentDetained <- append(DefendantsConcurrentDetained, temp)
} else if(defConcRel$get(defendants_concurrent[d])$ReleaseIndicator[r] == 1) {
temp1 <- defendants_concurrent[d]
DefendantsConcurrentReleased <- append(DefendantsConcurrentReleased, temp1)
}
}
}
# List of IR#s with concurrent cases and conflicting release indicators
DefendantsConcurrentConflicting <- Reduce(intersect, list(DefendantsConcurrentDetained, DefendantsConcurrentReleased))
# An example of conflicting release indicator 0,1 -> 1449149 categorized as detained.
for(i in 1:nrow(gunFelonyData_Conc)){
if(gunFelonyData_Conc$CRIRNBR[i] %in% DefendantsConcurrentDetained) {
gunFelonyData_Conc$Release[i] <- 0
}
}
# 1449149 categorized as detained for all concurrent cases.
```
```{r concCasesDefendants}
# Number of defendants with concurrent cases
length(unique(gunFelonyData_Conc$CRIRNBR))
```
```{r concCases#}
# Number of concurrent cases
length(unique(gunFelonyData_Conc$CRCASEN))
```
```{r concConfReleases}
# Number of defendants with concurrent cases and conflicting release indicators
length(unique(DefendantsConcurrentConflicting))
```
1,156 defendants had a total of 2,948 concurrent cases pending against them. In case of a conflict in their release indicator (detained or released), we've updated their records for detained to take precedence over released. There are 301 defendants with concurrent pending cases who also had conflicting release indicators.
```{r updateConcConfRelease}
# Update case-level records for concurrent cases with conflicting release indicator
gunFelonyConcConf <- gunFelonyData_Conc[gunFelonyData_Conc$CRIRNBR %in% DefendantsConcurrentConflicting,]
for(c in 1:length(gunFelonyData$CRCASEN)){
if(gunFelonyData$CRCASEN[c] %in% gunFelonyConcConf$CRCASEN) {
gunFelonyData$Release[c] <- 0
}
}
```
```{r CalculateCountofCharges}
# Get all columns that contain CLAOIC codes
ChargesCountCols <- grep("CLAOIC", names(gunFelonyData), value = TRUE)
for(c in 1:length(gunFelonyData$CRCASEN)) {
df = subset(gunFelonyData, CRCASEN == gunFelonyData$CRCASEN[c])
temp <- df[,ChargesCountCols]
naCount <- sum(is.na(temp))
# Create a new variable with # of charge counts (calculated as length of CLAOIC cols - empty cells)
gunFelonyData$`Charge Count (AOICs)`[c] <- length(ChargesCountCols) - naCount
}
```
```{r CalcDetentionLength}
# Calculate the length of detention
# Difference between Outcome / Sentence date and Arrest date for those detained.
# Difference between First Release date and Arrest date for those detained and released on (I-Bond and EM)
# Detained - Release indicator = 0
gunFelonyDataR0 <- subset(gunFelonyData, Release == 0)
# Detained - Release indicator = 1
gunFelonyDataR1 <- subset(gunFelonyData, Release == 1)
for(c in 1:length(gunFelonyData$CRCASEN)){
if(gunFelonyData$CRCASEN[c] %in% gunFelonyDataR0$CRCASEN){
gunFelonyData$Detention_Length[c] <- difftime(gunFelonyData$OutComeDt[c], gunFelonyData$CRARRDTE[c],
units = c("days"))
# Convert days to months
gunFelonyData$Detention_Length[c] <- gunFelonyData$Detention_Length[c]/30.5
gunFelonyData$Detention_Length[c] <- round(gunFelonyData$Detention_Length[c], digits = 1)
} else if(gunFelonyData$CRCASEN[c] %in% gunFelonyDataR1$CRCASEN){
gunFelonyData$Detention_Length[c] <- difftime(gunFelonyData$FirstRelDate[c], gunFelonyData$CRARRDTE[c],
units = c("days"))
# Convert days to months
gunFelonyData$Detention_Length[c] <- gunFelonyData$Detention_Length[c]/30.5
gunFelonyData$Detention_Length[c] <- round(gunFelonyData$Detention_Length[c], digits = 1)
}
}
colnames(gunFelonyData)[colnames(gunFelonyData) == "Detention_Length"] <- "Detention_Length (Months)"
# Replace NA with 0
gunFelonyData$`Detention_Length (Months)`[is.na(gunFelonyData$`Detention_Length (Months)`)] <- 0
```
```{r CalcPreTrialLength}
# Calculate the length of PreTrial
# Difference between Case Outcome date and Arrest date
for(c in 1:length(gunFelonyData$CRCASEN)){
gunFelonyData$Pretrial_Length[c] <- difftime(gunFelonyData$OutComeDt[c], gunFelonyData$CRARRDTE[c],
units = c("days"))
gunFelonyData$Pretrial_Length[c] <- gunFelonyData$Pretrial_Length[c]/30.5
gunFelonyData$Pretrial_Length[c] <- round(gunFelonyData$Pretrial_Length[c], digits = 1)
}
colnames(gunFelonyData)[colnames(gunFelonyData) == "Pretrial_Length"] <- "Pretrial_Length (Months)"
# Replace NA with 0
gunFelonyData$`Pretrial_Length (Months)`[is.na(gunFelonyData$`Pretrial_Length (Months)`)] <- 0
```
For those defendants detained for the entirety of the their pretrial period, the detention length and pretrial period should be the same or very close to eachother.
```{r Sentences}
# Sum total IDOC and CCDOC length
gunFelonyData$CCDOC_Sent2 <- as.integer(gunFelonyData$CCDOC_Sent)
gunFelonyData$CCDOC_Sent2[is.na(gunFelonyData$CCDOC_Sent2)] <- 0
gunFelonyData$IDOC_Sent <- as.integer(gunFelonyData$IDOC_Sent)
gunFelonyData$IDOC_Sent[is.na(gunFelonyData$IDOC_Sent)] <- 0
gunFelonyData$Corrections_Total <- as.integer(gunFelonyData$IDOC_Sent + gunFelonyData$CCDOC_Sent2)
gunFelonyData$Corrections_Total[is.na(gunFelonyData$Corrections_Total)] <- 0
colnames(gunFelonyData)[colnames(gunFelonyData) == "Corrections_Total"] <- "Corrections_Total (Months)"
gunFelonyData$SentCompletionDate <- AddMonths(as.Date(gunFelonyData$OutComeDt),
gunFelonyData$`Corrections_Total (Months)`)
pSent <- ggplot(gunFelonyData, aes(x=SentCompletionDate)) +
geom_histogram(binwidth = 20) +
#geom_vline(xintercept = quantile, size = 2) +
scale_x_date(breaks = date_breaks("2 years"),
labels=date_format("%b-%Y")) +
xlab("Sentence Completion Dates") +
theme_light() +
theme(axis.text.x = element_text(angle = 85, size = 8, hjust = 1))
pSent
```
Based on the computed sentence completion dates, it appears that the high concentration of cases had the date between 2014 and 2019.
```{r sentCompletionDate1YearAnniversary}
# Our post adjudication Re-Offense would be relative to individual's case completion and sentence completion date
# Calculate 1 year sentence completion anniversary date (I know anniversary has a celebratory connotation to it, but according to dictionary definition, it is a annual recurrence of the date of a past event - http://www.dictionary.com/browse/anniversary?s=t)
gunFelonyData$SentCompletionDate1YearAnniversary <- AddMonths(as.Date(gunFelonyData$SentCompletionDate),12)
```
```{r AgeCalculation - juvenile - case initiation date}
# Calculate whether the defendant is Juvenile or Adult by calculating age at the time of initial case date
for(i in 1:nrow(gunFelonyData)) {
gunFelonyData$`Defendant_Age (in years | Case initiation date)`[i] <- round(difftime(gunFelonyData$CRFRSTDT[i],
gunFelonyData$CRDOB[i],
units = c("days"))/365, digits = 0)
}
# Subset Juvenile defendants
gunFelonyData <- subset(gunFelonyData, `Defendant_Age (in years | Case initiation date)` > 17)
```
```{r AgeCalculation - predictor variable - outcome date}
# Calculate age at the time of sentence completion
for(i in 1:nrow(gunFelonyData)) {
gunFelonyData$`Defendant_Age (in years | Sentence comp date)`[i] <- round(difftime(gunFelonyData$SentCompletionDate[i],
gunFelonyData$CRDOB[i],
units = c("days"))/365, digits = 0)
}
```
```{r}
# Rearrange gun felony data
gunFelonyData <- subset(gunFelonyData, select = c(1:37,747:length(gunFelonyData),38:length(felonyData)))
```
### Merge CPD data for re-arrest target variable
```{r Import}
#Change Working Directory
# setwd("/export/projects/courtdata/CJO Pre-Trial Detention/data_raw/CPD_Arrests/")
#
# # Read Crime data
# ImportCSV <- function(files) {
#
# # Create a null dataframe
# myData <- data.frame(NULL)
#
# # Loop through each files in the list
# for (i in 1:length(files)) {
# cur.file <- read.csv(file = files[i], sep = ",", stringsAsFactors = FALSE)
# print(files[i])
# # Append data from current file to dataframe
# myData <- rbind(myData, cur.file)
# }
#
# return(myData)
#
# }
#
# # Grab all the csv files in the folder
# files <- list.files(path = "/export/projects/courtdata/CJO Pre-Trial Detention/data_raw/CPD_Arrests/",
# pattern = "*.csv")
#
# CPDArrestsData <- ImportCSV(files)
```
```{r}
getwd()
```
```{r cpdData}
#saveRDS(CPDArrestsData, file = "CPDArrestsData.rds")
CPDArrestsData <- readRDS("/export/projects/courtdata/CJO Pre-Trial Detention/analysis/KSanalysis/Code/CPDArrestsData.rds")
# Factorize IR_NO column
CPDArrestsData$IR_NO <- as.factor(CPDArrestsData$IR_NO)
CPDArrestsData$CB_NO <- as.factor(CPDArrestsData$CB_NO)
CPDArrestsData$ARREST_DATE1 <- as.Date(CPDArrestsData$ARREST_DATE, format = "%d-%b-%y")
```
```{r mergeCPD-ExactAndProbabilisticMatch}
# Truncate leading zeros for match with CPD Arrest data
gunFelonyData$CRCBNBR <- sub("^[0]+","",gunFelonyData$CRCBNBR)
# Matches based on Case #
gunFelonyCourtArrests_M1 <- merge(x = gunFelonyData, y = CPDArrestsData, by.x = "CRCBNBR", by.y = "CB_NO")
# Subset non-matches rows
gunFelonyDataNM <- subset(gunFelonyData,
!(gunFelonyData$CRCASEN %in% gunFelonyCourtArrests_M1$CRCASEN))
# Further match on IR# and Arrest date
gunFelonyCourtArrests_M2 <- merge(x = gunFelonyDataNM, y = CPDArrestsData,
by.x = c("CRIRNBR","CRARRDTE"),
by.y = c("IR_NO","ARREST_DATE1"))
# Drop columns IR_NO and ARR_DT
vars <- names(gunFelonyCourtArrests_M1) %in% c("IR_NO", "ARREST_DATE1")
gunFelonyCourtArrests_M1 <- gunFelonyCourtArrests_M1[!vars]
# Drop column CB_NO
vars <- names(gunFelonyCourtArrests_M2) %in% "CB_NO"
gunFelonyCourtArrests_M2 <- gunFelonyCourtArrests_M2[!vars]
# Append
gunFelonyCourtArrests <- rbind(gunFelonyCourtArrests_M1, gunFelonyCourtArrests_M2)
#gunFelonyCourtArrests <- subset(gunFelonyCourtArrests, select = c(1:55,756:872,56:755))
# Subset non-matches rows
gunFelonyDataNM1 <- subset(gunFelonyData,
!(gunFelonyData$CRCASEN %in% gunFelonyCourtArrests$CRCASEN))
```
```{r}
# Check if all IR#s in non matches belong to CPD Arrest data
gunFelonyDataIRNM1 <- unique(gunFelonyDataNM1$CRIRNBR)
CPDArrestsDataIR <- unique(CPDArrestsData$IR_NO)
gunFelonyDataIRNM1CPDArrest <- list()
gunFelonyDataIRNM1NoCPDArrest <- list()
for(i in 1:length(gunFelonyDataIRNM1)) {
if(gunFelonyDataIRNM1[i] %in% CPDArrestsDataIR) {
temp <- gunFelonyDataIRNM1[i]
gunFelonyDataIRNM1CPDArrest <- append(gunFelonyDataIRNM1CPDArrest, temp)
} else {
temp1 <- gunFelonyDataIRNM1[i]
gunFelonyDataIRNM1NoCPDArrest <- append(gunFelonyDataIRNM1NoCPDArrest, temp1)
}
}
```
```{r read - CPD gun violence identification file}
CPDguncharges <- readLines("gun_charges_flag.txt")
CPDguncharges
```
### Construct Arrest histories and our target / outcome variable - Arrests post adjudication
```{r ConstructArrestHistory}
# Iterate over IR # of each defendant with multiple cases open against them
defendants1 <- unique(gunFelonyCourtArrests$CRIRNBR)
# Create a dict object to store Arrest dates and charge characteristics
mdictArrest <- dict()
for(d in 1:length(defendants1)) {
df <- subset(CPDArrestsData[,c("ARREST_DATE1",
"IR_NO",
"STAT_DESCR",
"CHARGE_CLASS_CD",
"CHARGE_TYPE_CD",
"IUCR_CODE_CD")],
IR_NO == as.character(defendants1[d]))
#print(paste0("Defendants", defendants1[d]))
mdictArrest[[ defendants1[d] ]] <- list(ArrestDate = df$ARREST_DATE1,
Stat_Descr = df$STAT_DESCR,
ChargeClass = df$CHARGE_CLASS_CD,
ChargeType = df$CHARGE_TYPE_CD,
IUCR_Code = df$IUCR_CODE_CD)
}
# Create a dict object to store case #, initial court date and outcome date
mdictCourt <- dict()
for(d in 1:length(defendants1)) {
df <- subset(gunFelonyData[,c("CRCASEN",
"CRIRNBR",
"CRFRSTDT",
"OutComeDt",
"SentCompletionDate",
"SentCompletionDate1YearAnniversary")],
CRIRNBR == as.character(defendants1[d]))
mdictCourt[[ defendants1[d] ]] <- list(CaseNo = df$CRCASEN,
IR_NO = df$CRIRNBR,
CaseDocketDate = df$CRFRSTDT,
CaseOutComeDate = df$OutComeDt,
SentCompletionDt = df$SentCompletionDate,
SentCompletionDate1YearAnniversary = df$SentCompletionDate1YearAnniversary)
}
```
```{r ConstructArrestHistory1}
# 1152515 - Multiple cases
# List to store arrest history dates
ArrestHistory <- numvecdict()
ReOffense <- numvecdict()
ReOffense1Year <- numvecdict()
MidDates <- numvecdict()
ArrestDates <- list()
for(d in 1:length(defendants1)) {
#print(defendants1[d])
if(length(mdictArrest$get(defendants1[d])$ArrestDate) > 0) {
for(d1 in 1:length(mdictCourt$get(defendants1[d])$CaseDocketDate)) {
#print(paste0("Court Loop", mdictCourt$get(defendants1[d])$CaseDocketDate[d1]))
for(a in 1:length(mdictArrest$get(defendants1[d])$ArrestDate)) {
#print(paste0("Arrest Loop", mdictArrest$get(defendants1[d])$ArrestDate[a]))
ArrestDateInt <- as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a])
SentCompletionDateInt <- as.Date(mdictCourt$get(defendants1[d])$SentCompletionDt[d1])
DocketDateInt <- as.Date(mdictCourt$get(defendants1[d])$CaseDocketDate[d1])
# Mid dates
if(dplyr::between(ymd(ArrestDateInt), ymd(DocketDateInt), ymd(SentCompletionDateInt))) {
#print(paste0("Mid Arrest block", mdictArrest$get(defendants1[d])$ArrestDate[a]))
MidDates$append_number(defendants1[d],
as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a]))
}
# Check if Arrest date is prior to court date - (Arrest History)
else if(mdictArrest$get(defendants1[d])$ArrestDate[a] <
mdictCourt$get(defendants1[d])$CaseDocketDate[d1]) {
#print(paste0("Arrest History block", mdictArrest$get(defendants1[d])$ArrestDate[a]))
#ArrestHistory[[ mdictCourt$get(defendants1[d])$CaseNo[d1] ]] <-
# as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a])
ArrestHistory$append_number(mdictCourt$get(defendants1[d])$CaseNo[d1],
as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a]))
#as.character(mdictArrest$get(defendants1[d])$Stat_Descr[a]))
}
# Check if Arrest date is post court date - (ReOffense)
else if(mdictArrest$get(defendants1[d])$ArrestDate[a] >
mdictCourt$get(defendants1[d])$SentCompletionDt[d1]) {
# --> Use Sentence Completion date for guilty vs not guilty
#print(paste0("ReOffense block", mdictArrest$get(defendants1[d])$ArrestDate[a]))
#ReOffense[[ mdictCourt$get(defendants1[d])$CaseNo[d1] ]] <-
# as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a])
ReOffense$append_number(mdictCourt$get(defendants1[d])$CaseNo[d1],
as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a]))
if(mdictArrest$get(defendants1[d])$ArrestDate[a] <
mdictCourt$get(defendants1[d])$SentCompletionDate1YearAnniversary[d1]) {
ReOffense1Year$append_number(mdictCourt$get(defendants1[d])$CaseNo[d1],
as.Date(mdictArrest$get(defendants1[d])$ArrestDate[a]))
}
}
}
}
}
}
```
```{r SubsetCols}
CLAOICs <- grep("CLAOIC", names(gunFelonyData), value = TRUE)
CLCHGDESs <- grep("CLCHGDES", names(gunFelonyData), value = TRUE)
CLCHGSECs <- grep("CLCHGSEC", names(gunFelonyData), value = TRUE)
CLAOICs <- CLAOICs[CLAOICs != "CLAOIC"]
CLCHGDESs <- CLCHGDESs[CLCHGDESs != "CLCHGDES"]