-
Notifications
You must be signed in to change notification settings - Fork 0
/
va_cs_webr.html
907 lines (821 loc) · 36.2 KB
/
va_cs_webr.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.5.55">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>va_cs_webr</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
</style>
<script src="va_cs_webr_files/libs/clipboard/clipboard.min.js"></script>
<script src="va_cs_webr_files/libs/quarto-html/quarto.js"></script>
<script src="va_cs_webr_files/libs/quarto-html/popper.min.js"></script>
<script src="va_cs_webr_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="va_cs_webr_files/libs/quarto-html/anchor.min.js"></script>
<link href="va_cs_webr_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="va_cs_webr_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="va_cs_webr_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="va_cs_webr_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="va_cs_webr_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
</head>
<body class="fullcontent">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<main class="content" id="quarto-document-content">
<pre class="{webr-r}"><code>#data setup
#programs
#https://www.bop.gov/inmates/fsa/docs/fsa_program_guide_2107.pdf
#https://www.bop.gov/inmates/fsa/docs/evidence_based_recidivism_reduction_programs.pdf
#for participants
prgnm = c("am,0", "am,0", "am,0", "am,0", "am,0", "am,1", "am,1", "am,1", #CWC
"brave,0", "brave,0", "brave,0", "brave,0", "brave,0", "brave,1", #spelling error below
"bcs,0", "bcs,0", "bcs,1", "bcs,1", #spelling error below
"resolve,0", "resolve,0", "resolve,1", "resolve,1",
"rdap,1", "rdap,1", "rdap,1", #CWC #spelling error below
"dbt,1", "dbt,1", #CWC #spelling error below
"sotrt,0", "sotrt,1", "sotrt,1",
"challenge,0", "challenge,0", "challenge,0", "challenge,0", "challenge,0", "challenge,0","challenge,1", "challenge,1", #CWC
"mhsd,0", "mhsd,0", "mhsd,1",
"stages,0", "stages,0", "stages,0", "stages,0", "stages,0", "stages,0", "stages,1", "stages,1", "stages,1", #CWC
#spelling errors
"bgs,0", "bgs,0",
"fbt,0", "fbt,0",
"brv,0", "brv,0",
"rdp,0", "rdp,0")
#for staff
prgnm2 = c("am",
"brave",
"bcs",
"resolve",
"rdap",
"dbt",
"sotrt",
"challenge",
"mhsd",
"stages",
#spelling errors
"brv",
"stg",
"resol")
#dataframe sizes: sizen - roster, sizen2 - program staff, sizen3 - 2nd roster
sizen = 50 #DO NOT CHANGE - THIS IS SIZE OF DATA BEING SAMPLED ABOVE
date1 = 2017
date2 = 2018
##staff
sizen2 = 80 #2017-2018 staff
sizen4 = 84 #2021-2022 staff
############################################
#####set up roster/recidivism dataframe#####
############################################
#create person-level dataframe
set.seed(80)
roster.prep <- data.frame(
#create names
client_names = ch_name(sizen),
#create age
age = round(rnorm(sizen,29,5)),
#create programs/returns to prison
#data being sampled is exactly 50
programs.temp = sample(prgnm, size=50, replace = FALSE),
#create dates in programs
dt = as.Date("2018-01-01") + round(rnorm(sizen, mean = 0, sd = 120))
) |>
#split programs/returns
mutate(programs = substr(programs.temp,1,nchar(programs.temp)-2),
ret = as.numeric(substr(programs.temp,nchar(programs.temp),nchar(programs.temp))),
#put in a random date to throw things off
dt = case_when(row_number() == sizen-3 ~ as.Date(paste0('2007/06/05')),
row_number() == sizen-20 ~ as.Date(paste0('1997/08/22')),
TRUE ~ dt),
#put in a random return values
ret = case_when(row_number() == sizen-10 ~ -1,
row_number() == sizen-30 ~ 11,
row_number() == sizen-17 ~ 2,
TRUE ~ ret)
) |>
select(-c(programs.temp))
#create duplicates
roster <- roster.prep |>
filter(row_number() %in% c(1:5)) |>
bind_rows(roster.prep)
###############################################################
#####set up roster/recidivism dataframe for updated roster#####
###############################################################
#create 1000 person dataframe
sizen3 = 1000
date3 = 2021
date4 = 2022
set.seed(20012)
roster.update <- data.frame(
client_names = ch_name(sizen3),
age = round(rnorm(sizen3,29,5)),
programs.temp = sample(prgnm, size=sizen3, replace = TRUE),
dt = as.Date("2022-01-01") + round(rnorm(sizen, mean = 0, sd = 120))
) |>
mutate(programs = substr(programs.temp,1,nchar(programs.temp)-2),
ret = as.numeric(substr(programs.temp,nchar(programs.temp),nchar(programs.temp)))
) |>
select(-c(programs.temp))
########################################
#####set up program staff dataframe#####
########################################
#create 80 person dataframe
set.seed(160)
staff <- data.frame(
staff = ch_name(sizen2,messy=TRUE),
prg = sample(prgnm2, size=sizen2, replace = TRUE)
)
set.seed(160)
staff.update <- data.frame(
staff = ch_name(sizen4,messy=TRUE),
prg = sample(prgnm2, size=sizen4, replace = TRUE)
)
#ANALYSIS TOGGLE
######################################
casestudydata <- function(csdata = "roster.csv", staffdata = "staff.csv", byyear = F) {
if (csdata == "roster.csv" & staffdata == "staff.csv") {valset <<- 0} else if (csdata == "rosterupdate.csv" & staffdata == "staffupdate.csv") {valset <<- 1}
ALL.BY <<- byyear
dataname1 <<- noquote(substr(csdata,1,nchar(csdata)-4))
dataname2 <<- noquote(substr(staffdata,1,nchar(staffdata)-4))
}
#csdata - set the roster program data to run (roster.csv or rosterupdate.csv)
#staffdata - set the staff data to run (staff.csv or staffupdate.csv)
#byyear - set to T or F (T is run analysis by year, F is run analysis overall years), default is F
casestudydata("rosterupdate.csv", "staffupdate.csv", F)
#ANALYSIS TOGGLE
######################################
roster <- if(valset==0) {roster} else {roster.update} #options: roster; roster.update
date1 <- if(valset==0) {date1} else {date3} #options: date1 (within roster); date3 (within roster.update)
date2 <- if(valset==0) {date2} else {date4} #options: date2 (within roster); date4 (within roster.update)
staff <- if(valset==0) {staff} else {staff.update} #options: staff; staff.update
######################################
#programs to remove per the CWC report
rm.pgms <- c("bcs", "brave", "sotrt", "mhsd", "resolve")
#deduplicate across all columns
roster.nodup <- roster[!duplicated(roster), ]
#clean program names
roster.clean <- roster.nodup |>
#fix programs, dates, and returns
mutate(programs_clean = case_when(programs == "bgs" ~ "bcs",
programs == "fbt" ~ "dbt",
programs == "brv" ~ "brave",
programs == "rdp" ~ "rdap",
TRUE ~ programs),
#dates - assume that wrong dates occurred in 2017
dt = case_when(year(dt) < 2017 ~ `year<-`(dt, 2017),
TRUE ~ dt),
#returns - assume that wrong returns should all be =1
ret = case_when(ret == -1 ~ 1,
ret == 2 ~ 1,
ret == 11 ~ 1,
TRUE ~ ret)
)
##create dataset of numerators and denominators
#recidivism rates overall
roster2.1 <- roster.clean |>
mutate(year = factor(year(dt))) |>
select(-c(client_names,age,programs)) |>
group_by(programs_clean) |>
count(ret) |>
mutate(clients_served = sum(n),
recid_rate_all = case_when(ret == 1 ~ round(n/clients_served,2),
ret == 0 ~ 0)
) |>
group_by(programs_clean) |>
slice(n()) |>
select(-c(ret, n)) |>
rename(clients_served_all = clients_served)
#recidivism rates by year
roster2.2 <- roster.clean |>
mutate(year = factor(year(dt))) |>
select(-c(client_names,age,programs)) |>
group_by(programs_clean,year) |>
count(ret,year) |>
mutate(clients_served = sum(n),
recid_rate_year= case_when(ret == 1 ~ round(n/clients_served,2),
ret == 0 ~ 0)
) |>
group_by(programs_clean,year) |>
slice(n()) |>
select(-c(ret, n)) |>
rename(clients_served_year = clients_served)
#combine data by programs to capture recidivism rates overall and by year
roster2 <- inner_join(roster2.1, roster2.2, by = "programs_clean")
#clean program names
staff.clean <- staff |>
mutate(programs_clean = case_when(prg == "resol" ~ "resolve",
prg == "brv" ~ "brave",
prg == "stg" ~ "stages",
TRUE ~ prg))
#create dataset of staff counts
staff2 <- staff.clean |>
select(-c(staff,prg)) |>
count(programs_clean) |>
rename(num_staff = n)
#create table dataset
tabout <- inner_join(roster2, staff2, by = ("programs_clean")) |>
select(-c(clients_served_all, clients_served_year)) |>
ungroup() |>
#if any years are missing, fill in
complete(year, nesting(programs_clean,num_staff),
fill = list(recid_rate_all = NA, recid_rate_year = NA)
) |>
#correct missing values for recid_rate_all since this is the overall recidivism rate across multiple years
group_by(programs_clean) |>
fill(recid_rate_all, .direction = "updown") |>
ungroup() |>
#create final program names for table
mutate(program_official = case_when(programs_clean == "am" ~ "Anger Management",
programs_clean == "bcs" ~ "Basic Cognitive Skills",
programs_clean == "brave" ~ "The Bureau Rehabilitation and Values Enhancement Program",
programs_clean == "challenge" ~ "Challenge Program",
programs_clean == "dbt" ~ "Dialectical Behavior Therapy",
programs_clean == "mhsd" ~ "Mental Health Step Down Program",
programs_clean == "rdap" ~ "Residential Drug Abuse Program",
programs_clean == "resolve" ~ "The Resolve Program",
programs_clean == "sotrt" ~ "Sex Offender Treatment Program",
programs_clean == "stages" ~ "Steps Toward Awareness, Growth, and Emotional Strength Program",
TRUE ~ programs_clean))
#for positioning in plotting
last <- tail(tabout$programs_clean,n=1)
#manage the data to produce recidivism rates
tabout2 <- inner_join(roster2, staff2, by = ("programs_clean")) |>
ungroup() |>
#if any years are missing, fill in
complete(year, nesting(programs_clean,num_staff),
fill = list(recid_rate_all = NA, recid_rate_year = NA)
) |>
#correct missing values for recid_rate_all since this is the overall recidivism rate across multiple years
group_by(programs_clean) |>
fill(c(recid_rate_all,clients_served_all), .direction = "updown")
#calculate average recidivism rate across programs from all years
unw.a <- round(mean(tabout2$recid_rate_all,na.rm=TRUE),2)
#calculate average recidivism rate across programs from year 1
unw.d1 <- round(mean(tabout2[which(tabout2$year==date1),]$recid_rate_year,na.rm=TRUE),2)
#calculate average recidivism rate across programs from year 2
unw.d2 <- round(mean(tabout2[which(tabout2$year==date2),]$recid_rate_year,na.rm=TRUE),2)
#JUST 5 PROGRAMS!
#calculate average recidivism rate across programs from all years
unw.a5 <- round(mean(tabout2[which(!tabout2$programs_clean %in% rm.pgms),]$recid_rate_all,na.rm=TRUE),2)
#calculate average recidivism rate across programs from year 1
unw.d15 <- round(mean(tabout2[which(tabout2$year==date1 & !tabout2$programs_clean %in% rm.pgms),]$recid_rate_year,na.rm=TRUE),2)
#calculate average recidivism rate across programs from year 2
unw.d25 <- round(mean(tabout2[which(tabout2$year==date2 & !tabout2$programs_clean %in% rm.pgms),]$recid_rate_year,na.rm=TRUE),2)
#manage the data to produce recidivism rates
#total clients served (all years, year1, year2)
total.a <- sum(tabout2[which(tabout2$year==date1),]$clients_served_all, na.rm=TRUE)
tabout2.wgt <- tabout2 |>
filter(year==date1) |>
mutate(recid_rate_all_w = clients_served_all*recid_rate_all)
w.a <- round(sum(tabout2.wgt$recid_rate_all_w)/total.a,2)
#total clients served (year 1)
total.d1 <- sum(tabout2[which(tabout2$year==date1),]$clients_served_year,na.rm=TRUE)
tabout2.wgt <- tabout2 |>
filter(year==date1) |>
mutate(recid_rate_year_w = clients_served_year*recid_rate_year)
w.d1 <- round(sum(tabout2.wgt$recid_rate_year_w,na.rm=TRUE)/total.d1,2)
#total clients served (year2)
total.d2 <- sum(tabout2[which(tabout2$year==date2),]$clients_served_year,na.rm=TRUE)
tabout2.wgt <- tabout2 |>
filter(year==date2) |>
mutate(recid_rate_year_w = clients_served_year*recid_rate_year)
w.d2 <- round(sum(tabout2.wgt$recid_rate_year_w,na.rm=TRUE)/total.d2,2)
#JUST 5 PROGRAMS!!!
#total clients served (all years)
total.a5 <- sum(tabout2[which(tabout2$year==date1 & !tabout2$programs_clean %in% rm.pgms),]$clients_served_all, na.rm=TRUE)
tabout2.wgt5 <- tabout2 |>
filter(!(programs_clean %in% rm.pgms) & year==date1) |>
mutate(recid_rate_all_w = clients_served_all*recid_rate_all)
w.a5 <- round(sum(tabout2.wgt5$recid_rate_all_w)/total.a5,2)
#total clients served (year 1)
total.d15 <- sum(tabout2[which(tabout2$year==date1 & !tabout2$programs_clean %in% rm.pgms),]$clients_served_year,na.rm=TRUE)
tabout2.wgt5 <- tabout2 |>
filter(!(programs_clean %in% rm.pgms) & year==date1) |>
mutate(recid_rate_year_w = clients_served_year*recid_rate_year)
w.d15 <- round(sum(tabout2.wgt5$recid_rate_year_w,na.rm=TRUE)/total.d15,2)
#total clients served (year2)
total.d25 <- sum(tabout2[which(tabout2$year==date2 & !tabout2$programs_clean %in% rm.pgms),]$clients_served_year,na.rm=TRUE)
tabout2.wgt5 <- tabout2 |>
filter(!(programs_clean %in% rm.pgms) & year==date2) |>
mutate(recid_rate_year_w = clients_served_year*recid_rate_year)
w.d25 <- round(sum(tabout2.wgt5$recid_rate_year_w,na.rm=TRUE)/total.d25,2)
</code></pre>
<pre class="{webr-r}"><code>#| context: interactive
#| editor-max-height: 500
#| editor-code-line-numbers: 4-5, 8-12
#build bar chart of recidivism rates across programs
#in the block below, change the values to update the plot as needed
###############################
ALL.BY <- F #F overall years; T by year)
CWC <- F #T remove 5 programs; F keep 10 programs
#plot colors
staffc <- "brown" #set color for staffing text
hlinew1 <- "orange" #set color for weighted line
hlinew2 <- "darkgrey" #set color for unweighted line
date1c <- "deepskyblue1" #set color for earlier data date/overall
date2c <- "darkolivegreen3" #set color for later data date
###############################
#filter or don't filter out programs for plotting
tabout.cwc <- tabout
invisible({if(CWC) tabout.cwc <- tabout |> filter(! programs_clean %in% rm.pgms)})
#years of data do you want to plot
dates <- as.numeric(c(date1,date2))
#custom title header of plot
titledates <- ifelse(length(dates)>=2 & date1 != date2, paste0(date1," - ",date2),
ifelse((dates==date1 | dates==date2) & ALL.BY, as.character(dates),
ifelse(!ALL.BY, date1, "")))
#which years/programs are missing data? (footer)
prg.NA <- tabout.cwc |>
filter(is.na(recid_rate_year)) |>
pull(program_official)
##plot it! this will plot recidivism rates with overlaid staffing text
rr <- ggplot(tabout.cwc |>
filter(if(ALL.BY) year %in% dates else year == date2) |>
mutate(recid_rate = case_when(ALL.BY ~ recid_rate_year,
!ALL.BY ~ recid_rate_all))
,aes(x=str_wrap(program_official, 32), y=recid_rate, fill=year)) +
geom_bar(position = "dodge",stat = "identity") +
geom_text(aes(label=ifelse(year==dates[2],paste(num_staff,"staff"),"")), vjust=-0.3, color = staffc) +
scale_fill_manual(values=c(date1c,date2c)) +
ylim(0,1) +
ylab("Recidivism Rate") +
xlab("EBBR Programs") +
ggtitle(paste0("Recidivism Rates across EBBR programs\n",titledates)) +
theme_classic() +
theme(axis.text.x = element_text(angle = 30, vjust = 1, hjust=1)) +
#remove legend if plotting overall (not by year)
{if(!ALL.BY) theme(legend.position="none")}+
#only print caption if a program is missing data
{if(length(prg.NA)!=0) labs(caption = capture.output(cat("The following programs were missing data in some years:", unique(toupper(prg.NA)), sep=" ")))}+
theme(plot.caption=element_text(hjust=0))
#which weights to plot
w <- if(ALL.BY & !CWC) c(w.d1,w.d2) else if(ALL.BY & CWC) {c(w.d15,w.d25)} else if(!ALL.BY & !CWC) {w.a} else {w.a5}
unw <- if(ALL.BY & !CWC) c(unw.d1,unw.d2) else if(ALL.BY & CWC) {c(unw.d15,unw.d25)} else if(!ALL.BY & !CWC) {unw.a} else {unw.a5}
#nudging labels based on number of programs in plot
nudge.w <- 0
nudge.unw <- 0
invisible({if(!CWC) (nudge.w <- -4) & (nudge.unw <- -8)})
#add recidivism weight averages to plot
rrfinal <- rr +
geom_hline(yintercept=w[1], linetype = "dashed", color = hlinew1, size = 1) +
{if(ALL.BY) geom_hline(yintercept=w[2], linetype = "dashed", color = hlinew1, size = 1)}+
geom_hline(yintercept=unw[1], linetype = "dashed", color = hlinew2, size = 1) +
{if(ALL.BY) geom_hline(yintercept=unw[2], linetype = "dashed", color = hlinew2, size = 1)}+
geom_label_repel(aes(label=lab, y=0.25), fill=hlinew1,
data = tabout.cwc |>
filter(if(ALL.BY) year %in% dates else year == date2) |>
mutate(recid_rate = case_when( ALL.BY ~ recid_rate_year,
!ALL.BY ~ recid_rate_all),
lab = case_when( ALL.BY & date1 != date2 ~ paste0(date1," Weighted avg: ",w[1],"\n",date2," Weighted avg: ",w[2]),
!ALL.BY & date1 != date2 ~ paste0(date1,"-",date2,"\nWeighted avg: ",w[1]),
ALL.BY & date1 == date2 ~ paste0(date1,"\nWeighted avg: ",w[1]))) |>
filter(programs_clean == last & year == date2),
#move unweighted label left or right on x axis
nudge_x = nudge.w,
min.segment.length = Inf) +
geom_label_repel(aes(label=lab, y=0.5), fill=hlinew2,
data = tabout.cwc |>
filter(if(ALL.BY) year %in% dates else year == date2) |>
mutate(recid_rate = case_when( ALL.BY ~ recid_rate_year,
!ALL.BY ~ recid_rate_all),
lab = case_when( ALL.BY & date1 != date2 ~ paste0(date1," Unweighted avg: ",unw[1],"\n",date2," Unweighted avg: ",unw[2]),
!ALL.BY & date1 != date2 ~ paste0(date1,"-",date2,"\nUnweighted avg: ",unw[1]),
ALL.BY & date1 == date2 ~ paste0(date1,"\nUnweighted avg: ",unw[1]))) |>
filter(programs_clean == last & year == date2),
#move unweighted label left or right on x axis
nudge_x = nudge.unw,
min.segment.length = Inf)
rrfinal</code></pre>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
// For code content inside modals, clipBoardJS needs to be initialized with a container option
// TODO: Check when it could be a function (https://github.com/zenorocha/clipboard.js/issues/860)
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</div> <!-- /content -->
</body></html>