#1: Import and Clean DF

knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(tidyverse)   
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✔ ggplot2 4.0.3     ✔ purrr   1.2.2
## ✔ tibble  3.3.1     ✔ dplyr   1.2.1
## ✔ tidyr   1.3.2     ✔ stringr 1.6.0
## ✔ readr   2.2.0     ✔ forcats 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(janitor)
## 
## Attaching package: 'janitor'
## The following objects are masked from 'package:stats':
## 
##     chisq.test, fisher.test
library(knitr)
library(dplyr)
library(stringr)
library(gt)
library(ggplot2)
 
ces_measures <- read_csv("calenviroscreen_measures_2021.csv",
                         show_col_types = FALSE) %>% clean_names()

ces_scores <- read_csv("calenviroscreen_scores_demog_2021.csv",
                       show_col_types = FALSE) %>% clean_names()

#2. CalEnviroScreen Datatsets

#2.1: Recoding the common varaiable

add_county_fips <- function(df) {
  df %>%
    mutate(
      census_tract = sprintf("%011.0f", census_tract),  # restore leading zero
      county_fips  = str_sub(census_tract, 1, 5)
    )
}

ces_measures <- add_county_fips(ces_measures)
ces_scores   <- add_county_fips(ces_scores)

#2.2: Identify environmental measure(s) of interest and summarize into a county-level value

ces_env <- ces_measures %>%
  group_by(county_fips) %>%
  summarise(
    n_tracts      = n(),
    avg_pm2_5     = mean(pm2_5,     na.rm = TRUE),
    avg_ozone     = mean(ozone,     na.rm = TRUE),
    avg_diesel_pm = mean(diesel_pm, na.rm = TRUE),
    .groups = "drop"
  )

#2.3: Summarize CalEnviroScreen score into a county level variable.

ces_score <- ces_scores %>%
  group_by(county_fips) %>%
  summarise(
    median_ces_score  = median(ces_4_0_score, na.rm = TRUE),
    n_tracts_no_score = sum(is.na(ces_4_0_score)),
    .groups = "drop"
  )

#3. Asthma ED Dataset

chhs_asthma_ed <- read_csv("chhs_asthma_ed.csv",
                       locale = locale(encoding = "windows-1252"),
                       show_col_types = FALSE) %>% clean_names()

#3.1: Geography

counties <- sort(setdiff(unique(chhs_asthma_ed$county), "CALIFORNIA"), method = "radix")
stopifnot(length(counties) == 58)
fips <- setNames(sprintf("06%03d", 2 * seq_along(counties) - 1), counties)  # CA county FIPS = odd 001..115
fips["CALIFORNIA"] <- "06000"  

chhs_asthma_ed <- chhs_asthma_ed %>%
  mutate(
    geo_level   = if_else(county == "CALIFORNIA", "State", "County"),
    county_name = if_else(county == "CALIFORNIA", "California",
                          str_to_title(county)),
    county_fips = unname(fips[county]),
    state_fips  = "06",
    state_abbr  = "CA"
  )

#3.2: Age group

age_min_lu <- c("All ages" = 0, "0-4" = 0, "5-17" = 5, "0-17" = 0,
                "18-64" = 18, "18+" = 18, "65+" = 65)
age_max_lu <- c("All ages" = 120, "0-4" = 4, "5-17" = 17, "0-17" = 17,
                "18-64" = 64, "18+" = 120, "65+" = 120)
chhs_asthma_ed <- chhs_asthma_ed %>%
  mutate(across(where(is.character), ~ str_replace_all(.x, "\uFFFD", "-"))) %>% 
  mutate(
    age_group = age_group %>%
      str_replace_all("\u2013", "-") %>%
      str_remove(" years"),
    age_min = unname(age_min_lu[age_group]),
    age_max = unname(age_max_lu[age_group])
  )

#3.3: Race/ethnicity

race_map <- c(
  "White" = "White", "Black" = "Black", "Hispanic" = "Hispanic",
  "AI/AN" = "AIAN", "Asian" = "Asian", "NHPI" = "NHPI",
  "Asian/PI" = "Asian_PI",
  "Multi-Race" = "Multiracial", "Multi-race" = "Multiracial"
)
 
chhs_asthma_ed <- chhs_asthma_ed %>%
  mutate(
    race_ethnicity = if_else(strata == "Race/ethnicity",
                             unname(race_map[strata_name]),
                             NA_character_)      
  )

#3.4: Strata type

chhs_asthma_ed <- chhs_asthma_ed %>%
  mutate(
    strata_type = case_when(
      strata == "Total population" ~ "total",
      strata == "Age groups"       ~ "age",
      strata == "Child vs. adult"  ~ "age_broad",
      strata == "Race/ethnicity"   ~ "race_ethnicity"
    ))

#3.5: Missing

chhs_asthma_ed <- chhs_asthma_ed %>%
  mutate(value_missing = as.integer(is.na(number_of_ed_visits) | is.na(age_adjusted_ed_visit_rate)))

#3.6: Subset to most recent year and county level data

most_recent <- chhs_asthma_ed %>%
  filter(year == max(year, na.rm = TRUE))

asthma_county_data <- most_recent %>%
  group_by(county) %>%
  summarize(
    avg_ed_visit_rate = mean(age_adjusted_ed_visit_rate, na.rm = TRUE),
    total_ed_visits = sum(number_of_ed_visits, na.rm = TRUE)
  )

#3.7: Subset: most recent year, county-level rows only

latest_year <- max(chhs_asthma_ed$year, na.rm = TRUE)
latest_year    
## [1] 2020
chhs_asthma_ed <- chhs_asthma_ed %>%
  filter(year == latest_year,
         geo_level == "County")

dim(chhs_asthma_ed)    
## [1] 812  17
write_csv(chhs_asthma_ed, paste0("chhs_asthma_ed_", latest_year, "_county.csv"), na = "")

#3.8: Select demographic strata of interest.

unique(chhs_asthma_ed$strata)
## [1] "Total population" "Child vs. adult"  "Age groups"       "Race/ethnicity"
demographic_strata <- most_recent %>%
  filter(strata %in% c("Total population", "Age groups", "Race/ethnicity"))

#3.9: Pivot table to only include one row per county

county_data <- demographic_strata %>%
  group_by(county) %>%
  summarize(
    total_ed_visits = sum(number_of_ed_visits, na.rm = TRUE),
   avg_ed_visit_rate = mean(age_adjusted_ed_visit_rate, na.rm = TRUE),
    .groups = "drop"
  )

#3.10: Pivot table to only include one row per county

strata_keep <- c("Total", "White", "Black", "Hispanic", "AIAN",
                 "Asian_PI", "NHPI", "Multiracial")

chhs_asthma_ed_2 <- chhs_asthma_ed %>%
  mutate(
    stratum = case_when(
      strata == "Total population" ~ "Total",
      strata == "Race/ethnicity"   ~ str_replace_all(
        strata_name,
        c("^AI/AN$"       = "AIAN",
          "^Asian/PI$"    = "Asian_PI",
          "^Multi-[Rr]ace$" = "Multiracial")
      )
    )
  ) %>%
  filter(stratum %in% strata_keep) %>%
  select(county_fips, county_name, year, stratum,
         n    = number_of_ed_visits,
         rate = age_adjusted_ed_visit_rate) %>%
  pivot_wider(
    names_from  = stratum,
    values_from = c(n, rate),
    names_glue  = "{.value}_{stratum}"
  )

#3.11: Calculating Ratio

chhs_asthma_ed_2 <- chhs_asthma_ed_2 %>%
  mutate(
    # combining character strings
    county_label = paste0(county_name, " County, CA"),
    # calculating a ratio (NA if White rate is missing or 0, to avoid Inf)
    rate_ratio_black_white = if_else(!is.na(rate_White) & rate_White > 0,
                                     rate_Black / rate_White, NA_real_),
    # aggregation across columns
    n_groups_rate_missing = rowSums(is.na(across(starts_with("rate_"))))
  )

#4. Combining Datasets

CES_COMBINE <- chhs_asthma_ed_2 %>%
  left_join(ces_env,   by = "county_fips") %>%
  left_join(ces_score, by = "county_fips")

stopifnot(nrow(CES_COMBINE) == 58,
          !anyDuplicated(CES_COMBINE$county_fips),
          !anyNA(CES_COMBINE$avg_pm2_5),
          !anyNA(CES_COMBINE$median_ces_score))

#5. Descriptive Statistics

desc_vars <- c("n_Total", "rate_Total", "rate_Black", "rate_White")

desc_stats <- chhs_asthma_ed_2 %>%
  summarise(across(all_of(desc_vars),
                   list(n_valid   = ~sum(!is.na(.x)),
                        n_missing = ~sum(is.na(.x)),
                        mean      = ~mean(.x, na.rm = TRUE),
                        sd        = ~sd(.x, na.rm = TRUE),
                        median    = ~median(.x, na.rm = TRUE),
                        min       = ~min(.x, na.rm = TRUE),
                        max       = ~max(.x, na.rm = TRUE)),
                   .names = "{.col}__{.fn}")) %>%
  pivot_longer(everything(), names_to = c("variable", "stat"), names_sep = "__") %>%
  pivot_wider(names_from = stat, values_from = value) %>%
  mutate(across(where(is.numeric), ~round(.x, 1)))

#6. Data Dictionary

dict_desc <- tribble(
  ~variable,                ~description,
  "county_fips",            "5-digit county FIPS code (state 06 + county); merge key",
  "county_name",            "California county name, title case",
  "county_label",           "County name combined with ' County, CA' (derived)",
  "year",                   "Data year (most recent available)",
  "n_Total",                "Number of asthma ED visits, all residents",
  "rate_Total",             "Age-adjusted asthma ED visit rate per 10,000, all residents",
  "rate_Black",             "Age-adjusted asthma ED visit rate per 10,000, Black residents",
  "rate_White",             "Age-adjusted asthma ED visit rate per 10,000, White residents",
  "rate_ratio_black_white", "rate_Black / rate_White (derived); NA if White rate is missing or 0",
  "n_groups_rate_missing",  "Count of rate columns (total + race groups) that are missing for the county (derived)",
  "avg_pm2_5",              "Mean of tract PM2.5 values in the county (CalEnviroScreen units)",
  "avg_ozone",              "Mean of tract ozone values in the county (CalEnviroScreen units)",
  "avg_diesel_pm",          "Mean of tract diesel PM values in the county (CalEnviroScreen units)",
  "median_ces_score",       "Median CalEnviroScreen 4.0 score across tracts in the county",
  "n_tracts",               "Number of census tracts in the county (derived)"
)

data_dictionary <- dict_desc %>%
  mutate(data_type = sapply(CES_COMBINE[variable], function(x) class(x)[1]),
         .after = variable)

kable(data_dictionary, caption = "Data dictionary for the final county-level dataset")
Data dictionary for the final county-level dataset
variable data_type description
county_fips character 5-digit county FIPS code (state 06 + county); merge key
county_name character California county name, title case
county_label character County name combined with ’ County, CA’ (derived)
year numeric Data year (most recent available)
n_Total numeric Number of asthma ED visits, all residents
rate_Total numeric Age-adjusted asthma ED visit rate per 10,000, all residents
rate_Black numeric Age-adjusted asthma ED visit rate per 10,000, Black residents
rate_White numeric Age-adjusted asthma ED visit rate per 10,000, White residents
rate_ratio_black_white numeric rate_Black / rate_White (derived); NA if White rate is missing or 0
n_groups_rate_missing numeric Count of rate columns (total + race groups) that are missing for the county (derived)
avg_pm2_5 numeric Mean of tract PM2.5 values in the county (CalEnviroScreen units)
avg_ozone numeric Mean of tract ozone values in the county (CalEnviroScreen units)
avg_diesel_pm numeric Mean of tract diesel PM values in the county (CalEnviroScreen units)
median_ces_score numeric Median CalEnviroScreen 4.0 score across tracts in the county
n_tracts integer Number of census tracts in the county (derived)

Standardizing column names prior to joining.

CES_COMBINE <- CES_COMBINE %>%
  mutate(county_name = tolower(county_name))

asthma_county_data <- asthma_county_data %>%
  mutate(county = tolower(county))
CES_COMBINE <- CES_COMBINE %>%
  left_join(
    asthma_county_data %>%
      select(county, avg_ed_visit_rate, total_ed_visits),
    by = c("county_name" = "county")
  )

#Visualization 1. Comparing Asthma ED Rates with County-level Environmental Measures

scatter_data <- CES_COMBINE %>%
  select(county_name, avg_ed_visit_rate,
         avg_pm2_5,
         avg_ozone,
         avg_diesel_pm) %>%
  pivot_longer(
    cols = c(avg_pm2_5,
             avg_ozone,
             avg_diesel_pm),
    names_to = "environmental_measure",
    values_to = "measure_value"
  ) %>%
  filter(
    !is.na(avg_ed_visit_rate),
    !is.na(measure_value)
  )

ggplot(scatter_data,
       aes(x = measure_value,
           y = avg_ed_visit_rate)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "lm", se = TRUE) +
  facet_wrap(
  ~environmental_measure,
  scales = "free_x",
  labeller = as_labeller(c(
    avg_diesel_pm = "Diesel PM",
    avg_ozone = "Ozone",
    avg_pm2_5 = "PM2.5"
  ))
)

  labs(
    title = "County-Level Asthma ED Rates by Environmental Measure",
    x = "Environmental Measure",
    y = "Asthma ED Rate"
  ) +
  theme_minimal()
## NULL

The figure reflects that Diesel PM and PM2.5 appear to have slight positive associations with asthma ED rates, while Ozone has a slight negative association.

#Visualization 2. Comparing Asthma ED Rates with Overall CES Measures

viz1_data <- CES_COMBINE %>%
  filter(!is.na(rate_Total), !is.na(median_ces_score))

cor_ces <- cor.test(viz1_data$rate_Total, viz1_data$median_ces_score,
                    method = "spearman", exact = FALSE)

ggplot(viz1_data, aes(x = median_ces_score, y = rate_Total)) +
  geom_point(size = 2.5, alpha = 0.7, color = "black") +
  geom_smooth(method = "lm", se = TRUE, color = "steelblue") +
  labs(
    title    = "Asthma ED Visit Rates vs. Environmental Burden, California Counties",
    subtitle = paste0("Spearman rho = ", round(cor_ces$estimate, 2),
                      ", p = ", signif(cor_ces$p.value, 2),
                      ", n = ", nrow(viz1_data), " counties"),
    x = "Median CalEnviroScreen 4.0 score of census tracts in county\n(higher = greater cumulative burden)",
    y = paste0("Age-adjusted asthma ED visits per 10,000 residents (", latest_year, ")"),
    caption = paste0("Each point is one county. Line is a linear trend with 95% confidence band.\n",
                     "Counties with suppressed asthma rates are excluded.\n",
                     "Sources: CHHS asthma ED visit data; CalEnviroScreen 4.0 (2021).")
  ) +
  theme_minimal(base_size = 12) +
  theme(plot.title.position = "plot",
        plot.caption = element_text(hjust = 0, size = 9))