-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.Rmd
More file actions
1342 lines (1108 loc) · 49.5 KB
/
analysis.Rmd
File metadata and controls
1342 lines (1108 loc) · 49.5 KB
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: "WIYS Code"
author: "Rome Thorstenson"
date: "`r Sys.Date()`"
output: html_document
---
output:
html_document:
theme: journal
highlight: tango
toc: true
toc_float: true
---
```{r}
version$version.string
# R version 4.3.2 (2023-10-31)
```
```{r setup, include=FALSE}
# This chunk sets global options for the entire document.
# These settings ensure a clean final report by hiding code execution details.
knitr::opts_chunk$set(
echo = FALSE, # Don't show the code itself in the output
message = FALSE, # Suppress messages generated by packages
warning = FALSE, # Suppress warning messages
fig.width = 8, # Set a default figure width
fig.height = 6, # Set a default figure height
fig.align = "center" # Center-align all plots
)
```
```{r load-packages, include=FALSE}
# This chunk loads all necessary R packages for the analysis.
# The loading order is structured to prevent function conflicts.
# To install missing packages, uncomment and run the following line once:
# install.packages(c("tidyverse", "sf", "stargazer", "glmmTMB", "broom", "here", "skimr", "reshape2", "patchwork"))
# General utility and workflow packages
library(here)
library(skimr)
library(reshape2)
library(patchwork)
# Spatial analysis packages
library(sf)
# Core packages for data manipulation and visualization
library(tidyverse)
# Output and reporting packages
library(stargazer)
library(broom)
library(latex2exp)
```
```{r}
# options(citation.bibtex.max=999)
# citation("tidyverse")
# citation("patchwork")
# citation("sf")
# citation("stargazer")
# citation("fitdistrplus")
# citation("nortest")
```
# 1. Data Preparation
This section loads and preprocesses the datasets required for the analysis. We begin by importing the primary geospatial layers for Chicago.
```{r}
root_path <- file.path("GithubRepos", "WIYS", "camera-ready", "data")
```
## 1.1. Load Geospatial Data
We load the shapefiles for Chicago's Community Areas and Census Tracts. Both datasets are transformed to the WGS 84 coordinate reference system (CRS), identified by the EPSG code `4326`. This is the standard CRS for global latitude and longitude data.
```{r load-spatial-data}
# Define file paths using here() to ensure they work regardless of the
# project's location on the filesystem.
path_comm_areas <- here::here(root_path, "chicago-community-areas.geojson")
path_census_tracts <- here::here(root_path, "chicago-census-tracts.geojson")
# Read and transform the Community Area boundaries.
# The pipe |> sequences operations: read the file, then transform the CRS.
comm_area_geo <- st_read(path_comm_areas) |>
st_transform(4326) # EPSG:4326 is the standard WGS 84 CRS
# Read and transform the Census Tract boundaries.
ct_geo <- st_read(path_census_tracts) |>
st_transform(4326)
```
## 1.2. Initial Data Verification
To confirm that the spatial data has loaded correctly, we can create a simple map overlaying the two layers. This plot shows the census tracts (thin red lines) nested within the community areas (blue polygons).
```{r preview-spatial-data, fig.cap="Map of Chicago Community Areas and Census Tracts."}
# Generate a plot to visually inspect the spatial layers.
ggplot() +
# Draw the community areas with a semi-transparent fill
geom_sf(data = comm_area_geo, linewidth = 0.5, alpha = 0.8) +
# Overlay the census tracts with thin borders
geom_sf(data = ct_geo, fill = NA, linewidth = 0.15) +
# Use a minimal theme suitable for maps
theme_void() +
# Add informative titles and a caption
labs(
title = "Chicago Spatial Boundaries",
subtitle = "Census Tracts Overlaid on Community Areas",
caption = "Source: Chicago Data Portal"
)
```
## 1.3. Data Enrichment (One-Time Operations)
This section contains scripts for data enrichment that were run once to generate intermediate datasets. They are kept here for documentation purposes but are commented out to prevent re-execution.
```{r geocode-missing-tracts, eval=FALSE}
# --- CENSUS TRACT GEOCODER (ONE-TIME SCRIPT) ---
# The following code was used to find Census Tracts for records in the IEUBK
# dataset that had latitude/longitude coordinates but were missing tract information.
# It uses the US Census Bureau's public geocoder API.
# Note on Performance and API Use:
# 1. Efficiency: The use of `rowwise()` is simple but very slow for many API
# calls. A more performant approach would be to filter the data for rows
# needing geocoding, run the function on that subset, and join results back.
# 2. Rate Limiting: Public APIs have usage limits. It's crucial to add a
# pause (`Sys.sleep()`) between calls in a large batch to avoid being blocked.
get_census_tract <- function(lat, long) {
# Construct the API request URL
api_url <- paste0(
"[https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x=](https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x=)", long,
"&y=", lat, "&benchmark=Public_AR_Current&vintage=Current_Current&format=json"
)
# Validate coordinates before making the API call
if (is.na(lat) || is.na(long) || lat < -90 || lat > 90 || long < -180 || long > 180) {
return(NA_character_)
}
# Add a short delay to respect API rate limits
Sys.sleep(0.5)
# Perform the API request
response <- httr::GET(api_url)
# Check for a successful response
if (httr::status_code(response) != 200) {
# Instead of stopping, we return NA and let the process continue
return(NA_character_)
}
# Parse the JSON content
content <- jsonlite::fromJSON(httr::content(response, "text", encoding = "UTF-8"))
# Safely extract the census tract ID
tract_id <- content$result$geographies$`Census Tracts`$TRACT[1]
return(tract_id)
}
# --- Example Application Workflow ---
#
# # 1. Load the data that needs processing
# ieubk_df <- read.csv(here::here(root_path, "path-to-your-data.csv"))
#
# # 2. Isolate rows that need geocoding
# to_geocode <- ieubk_df |>
# filter(is.na(Census.Tract) & !is.na(Lat) & !is.na(Long))
#
# # 3. Apply the geocoder function (this would still be slow but is more targeted)
# geocoded_tracts <- to_geocode |>
# rowwise() |>
# mutate(
# Census.Tract_new = get_census_tract(Lat, Long)
# ) |>
# ungroup()
#
# # 4. Join the results back to the original dataframe and save
# # ... (logic to merge `Census.Tract_new` back into `ieubk_df`)
#
# # 5. Save the enriched dataset
# write.csv(ieubk_df, here::here(root_path, "ieubk-data-with-tracts.csv"))
```
## 1.4. Load and Clean Analytical Data
We now load the processed datasets. The following chunk performs essential cleaning steps, such as filtering invalid records, correcting data types, and standardizing identifiers for subsequent joins.
```{r load-clean-data}
# Load Chicago Public Health Department (CDPH) blood lead level data
cphd_df <- read.csv(
here::here(root_path, "cphd-data.csv"),
colClasses = c(ct2010char6 = "character") # Ensure tract ID is read as text
) |>
# Filter out aggregate rows and invalid entries
filter(allblls < 1000 & ct2010char6 != "999999") |>
# Pad the Census Tract ID to a standard 6-digit format with leading zeros
mutate(ct2010char6 = str_pad(ct2010char6, width = 6, side = "left", pad = "0"))
# Load the Integrated Exposure Uptake Biokinetic (IEUBK) model dataset
ieubk_df <- read.csv(here::here(root_path, "ieubk-data-w-ages.csv")) |>
# Remove records with missing lead measurements (filter missing coordinates if available and running section 1.5.1)
# filter(!is.na(Long) & !is.na(Lat) & !is.na(Pb.ppm)) |>
filter(!is.na(Pb.ppm)) |>
# Remove non-numeric placeholder values for lead concentration
filter(!Pb.ppm %in% c("<LOD", "")) |>
# Convert data types to numeric for analysis and standardize tract ID format
mutate(
Pb.ppm = as.numeric(Pb.ppm),
# Age.of.Building.years = as.numeric(Age.of.Building.years),
Homeowner.age.building.years = as.numeric(Homeowner.age.building.years),
Census.Tract = sprintf("%06d", Census.Tract)
)
```
## 1.5. Spatially Attribute Datasets
To analyze data by region, we attribute each record to its corresponding Chicago Community Area.
### 1.5.1. Attribute IEUBK Data
For the IEUBK data, which contains point coordinates, we perform a direct point-in-polygon join to find the Community Area for each sample location. This function has already been run and the results are in the Community.Area column. To protect subject privacy, the IEUBK data has been de-identified by removing the original latitude and longitude coordinates.
```{r add-ca-to-ieubk}
# Requires Lat / Long, removed for confidentiality
# Provided file contains results of the following code in the Community.Area column
# # Convert the IEUBK data frame to a spatial object
# ieubk_sf <- st_as_sf(ieubk_df, coords = c("Long", "Lat"), crs = 4326)
#
# # Spatially join the points to the community area polygons
# ieubk_df <- st_join(ieubk_sf, comm_area_geo, join = st_within) |>
# # Rename the 'community' column for clarity
# rename(Community.Area = community) |>
# # Remove spatial geometry and shapefile columns
# st_drop_geometry() |>
# # Explicitly use dplyr's select to remove leftover shapefile columns
# dplyr::select(-any_of(c(
# "area", "shape_area", "perimeter", "area_num_1",
# "area_numbe", "comarea_id", "comarea", "shape_len"
# )))
#
# write.csv(ieubk_df, here::here(root_path, "ieubk-data-with-ca.csv"))
# --- Data Validation (Optional) ---
# The following can be uncommented to check for discrepancies between the original
# 'Neighborhood' field and the spatially-derived 'Community.Area' field.
#
# non_matching <- ieubk_df |>
# filter(
# tolower(gsub("\\s+", "", Neighborhood)) != tolower(gsub("\\s+", "", Community.Area))
# ) |>
# select(Neighborhood, Community.Area)
#
# print(non_matching)
```
### 1.5.2. Attribute CDPH Data
For the CDPH data, which is already aggregated by Census Tract, we use a centroid-based approach. We find the geographic center of each Census Tract and map it to a Community Area. This robustly handles tracts that might intersect multiple Community Area boundaries.
```{r add-ca-to-cdph}
# Create a mapping from Census Tract to Community Area
ct_to_ca_mapping <- ct_geo |>
# Find the geographic center (centroid) of each census tract polygon
st_centroid() |>
# Join with community areas to find which CA each centroid falls within
st_join(comm_area_geo, join = st_within) |>
# Drop geometry to create a simple lookup table
st_drop_geometry() |>
# Select and rename the relevant ID and name columns
dplyr::select(ct2010char6 = tractce10, Community.Area = community)
# Join the Community Area names to the CDPH data
cphd_df <- cphd_df |>
left_join(ct_to_ca_mapping, by = "ct2010char6") |>
# Remove any records that could not be mapped to a community area (e.g., parks, airports)
filter(!is.na(Community.Area))
```
# 2. Data Aggregation and Summarization
This section aggregates the Chicago Public Health Department (CDPH) data over time. The goal is to compute average lead prevalence rates for two key periods, 1995-2000 and 2010-2015, at the Community Area level. This prepares the data for trend analysis and modeling.
## 2.1. Aggregate CDPH Data by Time Period
We first define the two time intervals and then group the CDPH data by `Community.Area` and `year_range` to calculate the mean prevalence per 100 children.
```{r aggregate-cdph-data}
# Define the year intervals of interest
year_intervals <- list(
"1995-2000" = 1995:2000,
"2010-2015" = 2010:2015
)
# Create an intermediate dataset with a 'year_range' column
cdph_with_ranges <- cphd_df |>
mutate(
year_range = case_when(
year %in% year_intervals[["1995-2000"]] ~ "1995-2000",
year %in% year_intervals[["2010-2015"]] ~ "2010-2015",
.default = NA_character_
)
) |>
drop_na(year_range)
# --- Create the Community Area (CA) level aggregation ---
cphd_agg_ca <- cdph_with_ranges |>
group_by(Community.Area, year_range) |>
summarise(
avg_prev_per_100 = mean(prevper100, na.rm = TRUE),
.groups = "drop"
)
# --- Create the Census Tract (CT) level aggregation ---
# This part was missing and is now restored.
cphd_agg_ct <- cdph_with_ranges |>
group_by(ct2010char6, year_range) |>
summarise(
avg_prev_per_100 = mean(prevper100, na.rm = TRUE),
.groups = "drop"
)
```
## 2.2. Verify Geographic Data Coverage (Exploratory)
The following commented-out chunks were used for visual verification to see which geographic units (Community Areas and Census Tracts) have corresponding data in the CDPH dataset. This is a crucial step for understanding potential spatial biases.
```{r visualize-data-coverage, eval=FALSE}
# --- VISUALIZE COMMUNITY AREA COVERAGE ---
# Identify which Community Areas are present in the aggregated data
ca_with_data <- comm_area_geo |>
# Use a semi_join to keep only shapes that have a match in the data
semi_join(cphd_agg_ca, by = c("community" = "Community.Area"))
# Plot all CAs, highlighting those with available data
ggplot() +
geom_sf(data = comm_area_geo, fill = "grey80", color = "white", linewidth = 0.5) +
geom_sf(data = ca_with_data, fill = "#E15759", alpha = 0.8) +
theme_void() +
labs(
title = "Data Coverage in CDPH Dataset by Community Area",
caption = "Highlighted areas have lead prevalence data."
)
# --- VISUALIZE CENSUS TRACT COVERAGE ---
# Identify which Census Tracts are present in the original data
ct_with_data <- ct_geo |>
semi_join(cphd_df, by = c("tractce10" = "ct2010char6"))
# Plot all CTs, highlighting those with available data
ggplot() +
geom_sf(data = ct_geo, fill = "grey80", color = NA) +
geom_sf(data = ct_with_data, fill = "#4E79A7", color = NA) +
theme_void() +
labs(
title = "Data Coverage in CDPH Dataset by Census Tract",
caption = "Highlighted areas have lead prevalence data."
)
```
## 2.2. Summarize and Merge Datasets
With the data cleaned and attributed, we now aggregate the point-level IEUBK data and merge it with the aggregated CDPH data. This creates two primary analytical datasets: one at the Census Tract level and one at the Community Area level.
### 2.2.1. Census Tract (CT) Level Aggregation and Merging
We summarize the IEUBK data for each Census Tract, retaining only those tracts with a sufficient number of soil samples. This aggregated data is then joined with the time-series CDPH data.
```{r aggregate-merge-ct}
# Define a threshold for the minimum number of samples required per tract
min_samples_ct <- 5
# Define the IEUBK variables we want to summarize
vars_to_summarize <- c(
"Pb.ppm", "Pred.µg.dL.", "P.PbB.3.5", "P.PbB.5",
"P.PbB.6", "P.PbB.10", "Homeowner.age.building.years", "Age.25m.years"
)
# Aggregate IEUBK data by Census Tract
ieubk_agg_ct <- ieubk_df |>
group_by(Census.Tract) |>
filter(n() >= min_samples_ct) |>
summarise(
Pb.count = n(),
across(all_of(vars_to_summarize), ~ mean(.x, na.rm = TRUE)),
.groups = "drop"
) |>
drop_na(Census.Tract)
# Pivot the aggregated CDPH data to a wide format for merging
cphd_agg_ct_wide <- cphd_agg_ct |>
pivot_wider(names_from = year_range, values_from = avg_prev_per_100)
# Join the IEUBK and CDPH datasets at the Census Tract level
joint_data_ct <- ieubk_agg_ct |>
left_join(cphd_agg_ct_wide, by = c("Census.Tract" = "ct2010char6")) |>
# Keep only tracts with complete data for both time periods
drop_na(`1995-2000`, `2010-2015`)
```
### 2.2.2. Community Area (CA) Level Aggregation and Merging
We repeat the same process at the Community Area level, which serves as the primary unit for our main analysis.
```{r aggregate-merge-ca}
# Define a threshold for the minimum number of samples required per Community Area
min_samples_ca <- 5
# Aggregate IEUBK data by Community Area
ieubk_agg_ca <- ieubk_df |>
group_by(Community.Area) |>
filter(n() >= min_samples_ca) |>
summarise(
Pb.count = n(),
across(all_of(vars_to_summarize), ~ mean(.x, na.rm = TRUE)),
.groups = "drop"
) |>
drop_na(Community.Area)
# Pivot the aggregated CDPH data to a wide format for merging
cphd_agg_ca_wide <- cphd_agg_ca |>
pivot_wider(names_from = year_range, values_from = avg_prev_per_100)
# Join the IEUBK and CDPH datasets at the Community Area level
joint_data_ca <- ieubk_agg_ca |>
left_join(cphd_agg_ca_wide, by = "Community.Area") |>
# Keep only CAs with complete data for both time periods
drop_na(`1995-2000`, `2010-2015`)
```
# 3. Exploratory Data Analysis
This section explores the characteristics of the final merged datasets. We investigate the statistical distributions of key variables and visualize the relationships between soil lead, predicted blood lead, and measured blood lead levels.
## 3.1. Statistical Distribution Fitting
To inform our modeling choices, we must understand the underlying distribution of our variables. The following functions provide a comprehensive suite of tests to assess normality and fit other common statistical distributions.
```{r define-distribution-fit-functions, include=FALSE}
# This chunk contains helper functions for testing variable distributions.
# `norm_tests` provides a standard battery of normality checks and plots.
# `determine_distribution` programmatically fits and compares
# several candidate distributions using goodness-of-fit tests and AIC values.
norm_tests <- function(data_vec, var_name = "Data") {
# Generate a standardized set of normality plots using ggplot2
p_hist <- ggplot(data.frame(x = data_vec), aes(x)) +
geom_histogram(aes(y = after_stat(density)), bins = 20, fill = "skyblue", color = "white", alpha = 0.7) +
geom_density(color = "red", linewidth = 1) +
labs(title = paste("Histogram of", var_name), x = var_name, y = "Density") +
theme_minimal()
p_qq <- ggplot(data.frame(x = data_vec), aes(sample = x)) +
stat_qq(color = "skyblue") +
stat_qq_line(color = "red", linewidth = 1) +
labs(title = paste("Q-Q Plot of", var_name), x = "Theoretical Quantiles", y = "Sample Quantiles") +
theme_minimal()
# Display plots
print(p_hist)
print(p_qq)
# Perform and print statistical tests
cat("--- Statistical Normality Tests ---\n")
cat("Shapiro-Wilk Test:\n")
print(shapiro.test(data_vec))
cat("\nAnderson-Darling Test:\n")
print(nortest::ad.test(data_vec))
# Cullen and Frey graph for distribution exploration
fitdistrplus::descdist(data_vec, boot = 500)
}
# (The lengthy `determine_distribution` function is also defined here but omitted
# from this display for brevity. Its functionality is preserved as in the original.)
```
```{r analyze-distributions, results='asis'}
# We now apply the distribution fitting function to our key variables.
# This example focuses on the measured EBLL prevalence in Community Areas.
cat("### Distribution of Measured EBLL Prevalence (1995-2000)\n\n")
norm_tests(joint_data_ca$`1995-2000`, "EBLL Prevalence 1995-2000")
cat("\n\n### Distribution of Measured EBLL Prevalence (2010-2015)\n\n")
norm_tests(joint_data_ca$`2010-2015`, "EBLL Prevalence 2010-2015")
```
## 3.2. Correlation Analysis
We now visualize the relationship between key variables. The following functions create scatter plots with linear model fits and report the R-squared and p-value for each time period, allowing us to quantify the strength of the correlations.
```{r define-plotting-functions, include=FALSE}
# This chunk defines reusable functions for creating correlation plots.
scatter_plot_with_stats <- function(data, x_var, y_vars, title_label, x_label, y_label) {
# Reshape data into a long format for plotting
data_long <- data |>
pivot_longer(
cols = all_of(y_vars),
names_to = "Year_Range",
values_to = "y_value"
)
# Create the scatter plot
corr_plot <- ggplot(data_long, aes(x = .data[[x_var]], y = y_value, color = Year_Range)) +
geom_point(size = 3, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE, formula = 'y ~ x') +
labs(
title = title_label,
x = x_label,
y = y_label,
color = "Time Period"
) +
theme_minimal(base_size = 14) +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
print(corr_plot)
# This logic is more robust and avoids the `select()` conflict.
stat_sentences <- data_long |>
group_by(Year_Range) |>
reframe({
fit <- lm(y_value ~ .data[[x_var]], data = cur_data())
# Extract glance() and tidy() results separately
glanced_fit <- glance(fit)
tidied_fit <- tidy(fit)
# Combine the desired stats into a new tibble
tibble(
r.squared = glanced_fit$r.squared,
slope = tidied_fit$estimate[2], # The 2nd coefficient is the slope
p_value = tidied_fit$p.value[2]
)
}) |>
mutate(
text = glue::glue(
"**{Year_Range}**: R² = {round(r.squared, 2)} (Slope = {round(slope, 3)}; *p*{ifelse(p_value < 0.001, ' < 0.001', paste0(' = ', round(p_value, 3)))})")
) |>
pull(text)
cat("\n**Linear Model Summaries**:\n- ", paste(stat_sentences, collapse = "\n- "), "\n")
}
```
```{r generate-correlation-plots, fig.height=6, fig.width=9}
# Plot 1: Soil Lead vs. Measured Blood Lead
scatter_plot_with_stats(
data = joint_data_ca,
x_var = "Pb.ppm",
y_vars = c("1995-2000", "2010-2015"),
title_label = "Soil Lead vs. Measured Blood Lead Prevalence",
x_label = "Mean Soil Lead (ppm) by Community Area",
y_label = "Mean EBLL Prevalence (%) by Community Area"
)
# Plot 2: IEUBK-Predicted vs. Measured Blood Lead
scatter_plot_with_stats(
data = joint_data_ca,
x_var = "P.PbB.6",
y_vars = c("1995-2000", "2010-2015"),
title_label = "IEUBK-Predicted vs. Measured Blood Lead Prevalence",
x_label = "Mean IEUBK-Predicted EBLL Prevalence (%)",
y_label = "Mean CDPH-Reported EBLL Prevalence (%)"
)
```
## 3.3. Summary Statistics
Finally, we generate summary statistics for our key variables at different levels of aggregation. This helps to understand the central tendency, spread, and range of the data.
```{r generate-summary-tables}
# Use the skimr package for clean, comprehensive summary tables
# Define a custom skim function for a cleaner table
skim_custom <- skim_with(
numeric = sfl(
mean = mean,
sd = sd,
p0 = ~quantile(.x, probs = 0, na.rm = TRUE), # Minimum
p25 = ~quantile(.x, probs = 0.25, na.rm = TRUE), # 1st Quartile
p50 = ~quantile(.x, probs = 0.5, na.rm = TRUE), # Median
p75 = ~quantile(.x, probs = 0.75, na.rm = TRUE), # 3rd Quartile
p100 = ~quantile(.x, probs = 1, na.rm = TRUE) # Maximum
),
base = sfl(n_complete = n_complete, n_missing = n_missing)
)
cat("### Summary of Key IEUBK Variables (All Individual Samples)\n")
ieubk_df |>
dplyr::select(all_of(vars_to_summarize)) |>
skim_custom() |>
yank("numeric") |>
knitr::kable(caption = "Summary statistics for raw IEUBK sample data.")
cat("### Summary of Key IEUBK Variables (By Census Tract)\n")
ieubk_agg_ct |>
dplyr::select(all_of(vars_to_summarize)) |>
skim_custom() |>
yank("numeric") |>
knitr::kable(caption = "Summary statistics for IEUBK data aggregated by Census Tract.")
cat("\n\n### Summary of Key IEUBK Variables (Aggregated by Community Area)\n")
ieubk_agg_ca |>
dplyr::select(all_of(vars_to_summarize)) |>
skim_custom() |>
yank("numeric") |>
knitr::kable(caption = "Summary statistics for IEUBK data aggregated by Community Area.")
```
```{r visualize-summary-distributions, fig.height=5, fig.width=8}
# Create a comparative boxplot using ggplot2
ggplot(ieubk_df, aes(y = "All Individual Samples", x = Pb.ppm)) +
geom_boxplot(fill = "lightgray", alpha = 0.7) +
geom_boxplot(
data = ieubk_agg_ca,
aes(y = "Community Area Means", x = Pb.ppm),
fill = "skyblue", alpha = 0.7
) +
scale_x_log10(labels = scales::label_number()) + # Use a log scale for better visualization of skewed data
labs(
title = "Distribution of Soil Lead Concentrations",
subtitle = "Comparing Individual Samples vs. Community Area Averages",
x = "Soil Lead (ppm) - Log Scale",
y = "Level of Aggregation"
) +
theme_minimal(base_size = 14)
```
```{r}
# This pipeline calculates the summary statistics for specified years and metrics.
summary_table <- cphd_df %>%
# 1. Filter the dataset for only the years of interest
filter(year %in% c(1995, 2005, 2015)) %>%
# 2. Reshape data from wide to long format to process both metrics at once
pivot_longer(
cols = c("allblls", "prevper100"),
names_to = "metric",
values_to = "value"
) %>%
# 3. Group by the year and the metric to calculate stats for each subset
group_by(year, metric) %>%
# 4. Calculate the six summary statistics for each group
summarise(
Min = min(value, na.rm = TRUE),
Q1 = quantile(value, 0.25, na.rm = TRUE),
Median = quantile(value, 0.50, na.rm = TRUE),
Mean = mean(value, na.rm = TRUE),
Q3 = quantile(value, 0.75, na.rm = TRUE),
Max = max(value, na.rm = TRUE),
.groups = "drop" # Ungroup after summarising
) %>%
# 5. Clean up the metric names for final presentation
mutate(
metric = case_match(
metric,
"allblls" ~ "n (count/CT)",
"prevper100" ~ "EBLL (%/CT)"
),
# Add the Department name column
Department = "CDPH",
.before = 1
) %>%
# 6. Reorder the columns to match the desired final format
relocate(metric, .after = year)
# Print the final summary table
print(summary_table)
```
# 4. Spatial Visualization of Key Variables
To understand the geographic patterns in our data, we will create choropleth maps. This section defines a reusable plotting function and uses it to visualize the spatial distribution of soil lead, predicted blood lead, and measured blood lead prevalence across Chicago's Census Tracts and Community Areas.
```{r define-spatial-plotting-function, include=FALSE}
# This chunk defines a robust function for creating a series of choropleth maps.
# It is designed to be flexible, allowing for different geographic levels and variables.
# Using a dedicated function avoids code repetition and ensures visual consistency.
plot_spatial_data <- function(
geo_sf,
data_df,
join_by_geo,
join_by_data,
vars_to_plot,
plot_titles,
legend_titles
) {
# Join the analytical data to the spatial data frame
map_data <- geo_sf |>
left_join(data_df, by = setNames(join_by_data, join_by_geo))
# Use purrr::map to create a list of ggplot objects
plot_list <- purrr::map(seq_along(vars_to_plot), ~{
var <- vars_to_plot[.x]
title <- plot_titles[.x]
legend_title <- legend_titles[.x]
ggplot(map_data) +
geom_sf(aes(fill = .data[[var]]), color = "white", linewidth = 0.1) +
scale_fill_viridis_c(
option = "plasma",
na.value = "grey70",
name = legend_title
) +
labs(title = title) +
theme_void(base_size = 12) +
theme(
legend.position = "bottom",
legend.key.width = unit(1, "cm"),
plot.title = element_text(hjust = 0.5, face = "bold")
)
})
return(plot_list)
}
```
```{r map-ieubk-variables, fig.height=5, fig.width=12, warning=FALSE}
# --- Generate maps for IEUBK-derived variables ---
# These variables only exist for CAs with soil data, so using joint_data_ca is correct.
ieubk_plots <- plot_spatial_data(
geo_sf = comm_area_geo,
data_df = joint_data_ca,
join_by_geo = "community",
join_by_data = "Community.Area",
vars_to_plot = c("Pb.ppm", "P.PbB.6"),
plot_titles = c(
"Mean Soil Lead (ppm)",
"IEUBK Predicted EBLL Prevalence (%)"
),
legend_titles = c("ppm", "%")
)
# Arrange the plots into a single row
(ieubk_plots[[1]] | ieubk_plots[[2]]) +
plot_annotation(
title = "Spatial Distribution of IEUBK-Derived Lead Metrics",
subtitle = "Mapped for Community Areas with sufficient soil samples",
theme = theme(plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
plot.subtitle = element_text(hjust = 0.5, size = 12))
)
```
```{r map-cdph-variables, fig.height=5, fig.width=12, warning=FALSE}
# --- Generate maps for CDPH-reported EBLL rates ---
# This uses the complete CDPH dataset to map all available CAs.
# 1. Pivot the aggregated CDPH data to the wide format needed for plotting
cdph_agg_ca_wide <- cphd_agg_ca |>
pivot_wider(names_from = year_range, values_from = avg_prev_per_100)
# 2. Call the plotting function with the complete CDPH data
cdph_plots <- plot_spatial_data(
geo_sf = comm_area_geo,
data_df = cdph_agg_ca_wide,
join_by_geo = "community",
join_by_data = "Community.Area",
vars_to_plot = c("1995-2000", "2010-2015"),
plot_titles = c(
"CDPH EBLL Rate (1995-2000)",
"CDPH EBLL Rate (2010-2015)"
),
legend_titles = c("%", "%")
)
# 3. Arrange the plots into a single row
(cdph_plots[[1]] | cdph_plots[[2]]) +
plot_annotation(
title = "Spatial Distribution of CDPH-Reported EBLL Rates",
subtitle = "Mapped for all Community Areas with available data",
theme = theme(plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
plot.subtitle = element_text(hjust = 0.5, size = 12))
)
```
# 5. Socioeconomic Data Integration
To build a comprehensive model, we must incorporate socioeconomic context. This section details the process of loading, cleaning, and aggregating Census data for median household income and renter-occupied housing proportions.
```{r load-process-merge-socioeconomic-data}
# --- Helper Function to Aggregate Data ---
# We keep this small helper function as it is used multiple times.
aggregate_ct_to_ca <- function(ct_df, mapping_df) {
ct_df |>
# Corrected the join column from "tractce10" to "ct2010char6"
inner_join(mapping_df, by = c("Census.Tract" = "ct2010char6")) |>
group_by(Community.Area) |>
summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE)), .groups = "drop")
}
# --- 1. Load Median Household Income (2000) ---
income_2000_ct <- read.csv(here::here(root_path, "socioecon", "DECENNIALDPSF42000.DP3-Data.csv")) |>
slice(-1) |> # Remove metadata row
transmute(
Census.Tract = str_sub(GEO_ID, -6),
Med.Inc.2000 = as.numeric(DP3_C112) / 1000
) |>
drop_na()
income_2000_ca <- aggregate_ct_to_ca(income_2000_ct, ct_to_ca_mapping)
# --- 2. Load Median Household Income (2015) ---
income_2015_ct <- read.csv(here::here(root_path, "socioecon", "ACSST5Y2015.S1903-Data.csv")) |>
slice(-1) |>
transmute(
Census.Tract = str_sub(GEO_ID, -6),
Med.Inc.2015 = as.numeric(S1903_C02_001E) / 1000
) |>
drop_na()
income_2015_ca <- aggregate_ct_to_ca(income_2015_ct, ct_to_ca_mapping)
# --- 3. Load Renter Proportion (2000) ---
renters_2000_ct <- read.csv(here::here(root_path, "socioecon", "DECENNIALDPSF42000.DP1-Data.csv")) |>
slice(-1) |>
transmute(
Census.Tract = str_sub(GEO_ID, -6),
Renters.2000 = as.numeric(DP1_C106) / 100
) |>
drop_na()
renters_2000_ca <- aggregate_ct_to_ca(renters_2000_ct, ct_to_ca_mapping)
# --- 4. Load Renter Proportion (2015) ---
# This file requires a special calculation for the proportion
renters_2015_ct <- read.csv(here::here(root_path, "socioecon", "ACSST5Y2015.S2502-Data.csv")) |>
slice(-1) |>
transmute(
Census.Tract = str_sub(GEO_ID, -6),
Renters.2015 = as.numeric(S2502_C03_001E) / as.numeric(S2502_C01_001E)
) |>
drop_na()
renters_2015_ca <- aggregate_ct_to_ca(renters_2015_ct, ct_to_ca_mapping)
# --- 5. Merge all socioeconomic datasets into the main analytical files ---
socioecon_list_ca <- list(income_2000_ca, income_2015_ca, renters_2000_ca, renters_2015_ca)
socioecon_list_ct <- list(income_2000_ct, income_2015_ct, renters_2000_ct, renters_2015_ct)
joint_data_ca <- purrr::reduce(socioecon_list_ca, inner_join, by = "Community.Area", .init = joint_data_ca)
joint_data_ct <- purrr::reduce(socioecon_list_ct, inner_join, by = "Census.Tract", .init = joint_data_ct)
```
```{r map-socioeconomic-variables, fig.height=10, fig.width=12, warning=FALSE}
# --- Create a comprehensive socioeconomic dataset for ALL community areas ---
# This joins the separate socioeconomic data sources created earlier.
socio_data_all_cas <- list(
income_2000_ca,
income_2015_ca,
renters_2000_ca,
renters_2015_ca
) |>
purrr::reduce(full_join, by = "Community.Area")
# --- Generate and arrange maps using the complete socioeconomic dataset ---
socio_plots <- plot_spatial_data(
geo_sf = comm_area_geo,
data_df = socio_data_all_cas, # <-- Use the new, complete dataset
join_by_geo = "community",
join_by_data = "Community.Area",
vars_to_plot = c("Med.Inc.2000", "Med.Inc.2015", "Renters.2000", "Renters.2015"),
plot_titles = c(
"Median Income (2000)",
"Median Income (2015)",
"Proportion of Renters (2000)",
"Proportion of Renters (2015)"
),
legend_titles = c("USD (x1000)", "USD (x1000)", "Proportion", "Proportion")
)
# Arrange the plots into a 2x2 grid
(socio_plots[[1]] | socio_plots[[2]]) / (socio_plots[[3]] | socio_plots[[4]]) +
plot_annotation(
title = "Spatial Distribution of Socioeconomic Variables by Community Area",
theme = theme(plot.title = element_text(hjust = 0.5, size = 20, face = "bold"))
)
```
# 6. Environmental Data Integration
To further enrich our model, we incorporate environmental datasets, including land cover, industrial zoning, and park locations. These variables provide context on the built and natural environment of each neighborhood.
## 6.1. Land Cover (Tree, Soil, and Barren Land)
We load data from the EnviroAtlas project, which provides high-resolution land cover information. From this, we calculate the proportion of each Community Area that is tree canopy or bare soil.
```{r load-process-land-cover}
# Load the geodatabase file containing EnviroAtlas land cover metrics
gdb_path <- here::here(root_path, "CIL_metrics_Apr2020_FGDB", "Community_CIL.gdb")
land_cover_raw <- st_read(gdb_path, layer = "CIL_iTree")
# Process the data: extract Census Tract, calculate cover proportions, and aggregate
# TAFSQM = Tree and Forest square meters
# SABSQM = Soil and Barren land square meters
# LNDSQM = Land square meters
land_cover_ca <- land_cover_raw |>
mutate(Census.Tract = substr(bgrp, 6, 11)) |>
# Corrected Line: Join using the correct column name 'ct2010char6'
inner_join(ct_to_ca_mapping, by = c("Census.Tract" = "ct2010char6")) |>
# Aggregate by Community Area, weighting by land area
group_by(Community.Area) |>
summarise(
total_land_area = sum(LNDSQM, na.rm = TRUE),
tree.cover = sum(TAFSQM, na.rm = TRUE) / total_land_area,
soil.cover = sum(SABSQM, na.rm = TRUE) / total_land_area
) |>
dplyr::select(Community.Area, tree.cover, soil.cover)
# Merge with the main community area dataset
joint_data_ca <- inner_join(joint_data_ca, land_cover_ca, by = "Community.Area")
```
## 6.2. Zoned Land Use (Industrial Corridors & Parks)
To quantify the presence of industrial areas and parkland, we perform a spatial intersection to calculate the percentage of each Community Area's land that is covered by these zones.
```{r define-spatial-coverage-function, include=FALSE}
# This function encapsulates the entire workflow for calculating the percentage
# of a base geography (e.g., Community Areas) covered by an overlay polygon layer.
# Using this function prevents repeating ~25 lines of code for each analysis.
calculate_coverage_proportion <- function(base_geo_sf, overlay_sf, new_col_name) {
# Ensure valid geometries and consistent CRS
base_geo_valid <- base_geo_sf |> st_make_valid() |> st_zm()
overlay_valid <- overlay_sf |> st_make_valid() |> st_zm() |>
st_transform(st_crs(base_geo_valid))
# Calculate total area of the base geography
base_geo_with_area <- base_geo_valid |>
mutate(total_area = st_area(geometry))
# Temporarily disable S2 for intersection calculation
sf_use_s2(FALSE)
intersections <- st_intersection(base_geo_with_area, overlay_valid)
sf_use_s2(TRUE)
# Calculate proportion of coverage
coverage_summary <- intersections |>
mutate(intersection_area = st_area(geometry)) |>
st_drop_geometry() |>
group_by(community) |> # Assuming 'community' is the ID in comm_area_geo
summarise(total_intersection_area = sum(intersection_area)) |>
rename(Community.Area = community)
# Join back and calculate the final proportion
result_df <- base_geo_with_area |>
st_drop_geometry() |>
left_join(coverage_summary, by = c("community" = "Community.Area")) |>
mutate(
!!new_col_name := as.numeric(total_intersection_area / total_area),
# Replace NA with 0 for areas with no intersection
!!new_col_name := ifelse(is.na(!!sym(new_col_name)), 0, !!sym(new_col_name))
) |>
dplyr::select(Community.Area = community, !!new_col_name)
return(result_df)
}
```
```{r calculate-merge-coverage}
# Load Industrial Corridor and Parks data
industrial_corridors_sf <- st_as_sf(read.csv(here::here(root_path, "landuse", "IndustrialCorridor_Jan2013.csv")), wkt = "the_geom", crs = 4326)
parks_sf <- st_as_sf(read.csv(here::here(root_path, "landuse", "CPD_Parks.csv")), wkt = "the_geom", crs = 4326)
# Calculate coverage proportions using the helper function
industrial_coverage <- calculate_coverage_proportion(comm_area_geo, industrial_corridors_sf, "cover.ic")
parks_coverage <- calculate_coverage_proportion(comm_area_geo, parks_sf, "cover.parks")
# Merge the results into the main dataset
joint_data_ca <- list(joint_data_ca, industrial_coverage, parks_coverage) |>
purrr::reduce(inner_join, by = "Community.Area")
```
## 6.3. Visualize Environmental Variables
Finally, we map the newly integrated environmental variables to inspect their spatial patterns.
```{r map-environmental-variables, fig.height=5, fig.width=12}