library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(readr)
library(ggplot2)
pop_data <- read_csv("CA_Pop_GeoStratified_export.csv")
## Rows: 90132 Columns: 12
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): county, health_officer_region, age_cat, sex, race_ethnicity, geo_de...
## dbl (6): population, geo_total_pop, geo_male_pop, geo_female_pop, sex_ratio_...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
morbidity_data <- read_csv("morbidity_data_combined_export.csv")
## Rows: 100688 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): county, age_category, sex, race_ethnicity, geo_designation
## dbl  (8): new_infections, cumulative_infected, new_unrecovered, cumulative_u...
## date (1): dt_diagnosis
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
pop_morbidity_data <- left_join(
  morbidity_data, 
  pop_data, 
  by = c(
    "county" = "county", 
    "age_category" = "age_cat", 
    "sex" = "sex", 
    "race_ethnicity" = "race_ethnicity", 
    "geo_designation" = "geo_designation"
  ),
  relationship = "many-to-many" 
)


head(pop_morbidity_data)
## # A tibble: 6 × 21
##   county  dt_diagnosis age_category sex    race_ethnicity      new_infections
##   <chr>   <date>       <chr>        <chr>  <chr>                        <dbl>
## 1 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 2 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 3 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 4 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 5 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 6 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## # ℹ 15 more variables: cumulative_infected <dbl>, new_unrecovered <dbl>,
## #   cumulative_unrecovered <dbl>, new_severe <dbl>, cumulative_severe <dbl>,
## #   geo_designation <chr>, morbidity_proportion <dbl>,
## #   severity_proportion <dbl>, health_officer_region <chr>, population <dbl>,
## #   geo_total_pop <dbl>, geo_male_pop <dbl>, geo_female_pop <dbl>,
## #   sex_ratio_m_per_100_f <dbl>, pct_population <dbl>
pop_morbidity_data <- pop_morbidity_data %>%
  mutate(
    urban_classification = case_when(
      county %in% c("Alameda", "Contra Costa", "Los Angeles", "Orange", 
                    "Riverside", "Sacramento", "San Bernardino", "San Diego", 
                    "San Francisco", "San Mateo", "Santa Clara") ~ "Urban",
      
      county %in% c("Butte", "El Dorado", "Fresno", "Imperial", "Kern", 
                    "Kings", "Madera", "Marin", "Merced", "Monterey", 
                    "Napa", "Placer", "San Benito", "San Joaquin", 
                    "San Luis Obispo", "Santa Barbara", "Santa Cruz", 
                    "Shasta", "Solano", "Sonoma", "Stanislaus", 
                    "Sutter", "Tulare", "Ventura", "Yolo", "Yuba") ~ "Semi-Urban",
      
      county %in% c("Amador", "Calaveras", "Colusa", "Del Norte", 
                    "Glenn", "Humboldt", "Lake", "Lassen", 
                    "Mendocino", "Nevada", "Tehama", "Tuolumne") ~ "Semi-Rural",
      
      county %in% c("Alpine", "Inyo", "Mariposa", "Modoc", 
                    "Mono", "Plumas", "Sierra", "Siskiyou", "Trinity") ~ "Rural",
      
      TRUE ~ "Unknown"
    )
  )
head(pop_morbidity_data)
## # A tibble: 6 × 22
##   county  dt_diagnosis age_category sex    race_ethnicity      new_infections
##   <chr>   <date>       <chr>        <chr>  <chr>                        <dbl>
## 1 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 2 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 3 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 4 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 5 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## 6 Alameda 2023-05-29   0-17         FEMALE White, Non-Hispanic              6
## # ℹ 16 more variables: cumulative_infected <dbl>, new_unrecovered <dbl>,
## #   cumulative_unrecovered <dbl>, new_severe <dbl>, cumulative_severe <dbl>,
## #   geo_designation <chr>, morbidity_proportion <dbl>,
## #   severity_proportion <dbl>, health_officer_region <chr>, population <dbl>,
## #   geo_total_pop <dbl>, geo_male_pop <dbl>, geo_female_pop <dbl>,
## #   sex_ratio_m_per_100_f <dbl>, pct_population <dbl>,
## #   urban_classification <chr>
summary_by_urbanity <- pop_morbidity_data %>%
  group_by(urban_classification) %>%
  summarize(
    total_population = sum(population, na.rm = TRUE),
    total_new_infections = sum(new_infections, na.rm = TRUE),
    
    record_count = n() 
  )

print(summary_by_urbanity)
## # A tibble: 4 × 4
##   urban_classification total_population total_new_infections record_count
##   <chr>                           <dbl>                <dbl>        <int>
## 1 Rural                         3978788               630988       406224
## 2 Semi-Rural                   19868675              2633590       541632
## 3 Semi-Urban                  266062057             44928567      1173536
## 4 Urban                       815848018             97428436       496496
# rural counties by new infections and sex

rural_counties <- pop_morbidity_data %>%
  filter(urban_classification == "Rural") %>%
  group_by(dt_diagnosis, sex) %>%
  summarise(total_cases = sum(new_infections, na.rm = TRUE))
## `summarise()` has grouped output by 'dt_diagnosis'. You can override using the
## `.groups` argument.
ggplot(rural_counties, aes(x= dt_diagnosis, y= total_cases, fill = sex)) +
  geom_col(position = "dodge") +
  labs(title = "New Infection Cases by Sex in Rural California in 2023",
       x = "Diagnosis Date",
       y = "New Infection Counts",
       fill = "Sex") 

# urban counties by morbidity proportion and sex

urban_counties <- pop_morbidity_data %>%
  filter(urban_classification == "Urban") %>%
  group_by(dt_diagnosis, sex) %>%
  summarise(morbidity_proportion = mean(morbidity_proportion, na.rm = TRUE))
## `summarise()` has grouped output by 'dt_diagnosis'. You can override using the
## `.groups` argument.
ggplot(urban_counties, aes(x= dt_diagnosis, y= morbidity_proportion,
                           color = sex, group = sex)) +
  geom_line(linewidth = 1) +
  geom_point() +
  labs(title = "Morbidity Proportion by Sex in Urban California in 2023",
       x = "Diagnosis Date",
       y = "Morbidity Proportion",
       color = "Sex") 

region_sex_severe <- pop_morbidity_data %>%
  filter(
    urban_classification != "Unknown",
    sex %in% c("MALE", "FEMALE")
  ) %>%
  mutate(
    urban_classification = factor(
      urban_classification,
      levels = c("Rural", "Semi-Rural", "Semi-Urban", "Urban")
    ),
    sex = ifelse(sex == "MALE", "Male", "Female")
  ) %>%
  group_by(urban_classification, sex) %>%
  summarise(total_severe_cases = sum(new_severe, na.rm = TRUE), .groups = "drop")

ggplot(region_sex_severe, aes(x = total_severe_cases, y = urban_classification, fill = sex)) +
  geom_col(position = "dodge") +
  scale_x_continuous(labels = scales::comma) +
  labs(
    title = "Severe Case Counts by Region and Sex",
    x = "Number of Severe Cases",
    y = "Region",
    fill = "Sex"
  ) +
  theme_minimal()

age_sex_severe <- pop_morbidity_data %>%
  filter(
    !is.na(age_category),
    sex %in% c("MALE", "FEMALE")
  ) %>%
  mutate(
    sex = ifelse(sex == "MALE", "Male", "Female")
  ) %>%
  group_by(age_category, sex) %>%
  summarise(total_severe_cases = sum(new_severe, na.rm = TRUE), .groups = "drop")

ggplot(age_sex_severe, aes(x = total_severe_cases, y = age_category, fill = sex)) +
  geom_col(position = "dodge") +
  scale_x_continuous(labels = scales::comma) +
  labs(
    title = "Severe Case Counts by Age Group and Sex",
    x = "Number of Severe Cases",
    y = "Age Group",
    fill = "Sex"
  ) +
  theme_minimal()

severe_by_region <- pop_morbidity_data %>%
  filter(urban_classification != "Unknown") %>%
  group_by(urban_classification) %>%
  summarise(
    total_severe_cases = sum(new_severe, na.rm = TRUE),
    .groups = "drop"
  )

pop_by_region <- pop_morbidity_data %>%
  filter(urban_classification != "Unknown") %>%
  distinct(county, age_category, sex, race_ethnicity, geo_designation, urban_classification, population) %>%
  group_by(urban_classification) %>%
  summarise(
    total_population = sum(population, na.rm = TRUE),
    .groups = "drop"
  )

severe_proportion_by_region <- left_join(severe_by_region, pop_by_region, by = "urban_classification") %>%
  mutate(
    urban_classification = factor(
      urban_classification,
      levels = c("Urban", "Semi-Urban", "Semi-Rural", "Rural")
    ),
    severe_proportion = total_severe_cases / total_population,
    severe_percent = severe_proportion * 100,
    severe_per_100k = severe_proportion * 100000
  ) %>%
  arrange(urban_classification)


print(severe_proportion_by_region)
## # A tibble: 4 × 6
##   urban_classification total_severe_cases total_population severe_proportion
##   <fct>                             <dbl>            <dbl>             <dbl>
## 1 Urban                           3570563         26153410             0.137
## 2 Semi-Urban                      1605949          8316662             0.193
## 3 Semi-Rural                       119741           564743             0.212
## 4 Rural                             31606           103216             0.306
## # ℹ 2 more variables: severe_percent <dbl>, severe_per_100k <dbl>
ggplot(severe_proportion_by_region, aes(x = urban_classification, y = severe_per_100k, fill = urban_classification)) +
  geom_col(show.legend = FALSE) +
  geom_text(aes(label = round(severe_per_100k, 1)), vjust = -0.5) +
  labs(
    title = "Severe Cases per 100,000 Population by Region",
    x = "Region",
    y = "Severe Cases per 100,000 People"
  ) +
  theme_minimal()

severe_by_region_sex <- pop_morbidity_data %>%
  filter(
    urban_classification != "Unknown",
    sex %in% c("MALE", "FEMALE")
  ) %>%
  group_by(urban_classification, sex) %>%
  summarise(
    total_severe_cases = sum(new_severe, na.rm = TRUE),
    .groups = "drop"
  )

pop_by_region_sex <- pop_morbidity_data %>%
  filter(
    urban_classification != "Unknown",
    sex %in% c("MALE", "FEMALE")
  ) %>%
  distinct(county, age_category, sex, race_ethnicity, geo_designation, urban_classification, population) %>%
  group_by(urban_classification, sex) %>%
  summarise(
    total_population = sum(population, na.rm = TRUE),
    .groups = "drop"
  )

severe_rate_region_sex <- left_join(
  severe_by_region_sex,
  pop_by_region_sex,
  by = c("urban_classification", "sex")
) %>%
  mutate(
    urban_classification = factor(
      urban_classification,
      levels = c("Urban", "Semi-Urban", "Semi-Rural", "Rural")
    ),
    sex = ifelse(sex == "MALE", "Male", "Female"),
    severe_per_100k = (total_severe_cases / total_population) * 100000
  ) %>%
  arrange(urban_classification, sex)

print(severe_rate_region_sex)
## # A tibble: 8 × 5
##   urban_classification sex   total_severe_cases total_population severe_per_100k
##   <fct>                <chr>              <dbl>            <dbl>           <dbl>
## 1 Urban                Fema…            1923234         13373057          14381.
## 2 Urban                Male             1647329         12780353          12890.
## 3 Semi-Urban           Fema…             850408          4248756          20015.
## 4 Semi-Urban           Male              755541          4067906          18573.
## 5 Semi-Rural           Fema…              60363           278334          21687.
## 6 Semi-Rural           Male               59378           286409          20732.
## 7 Rural                Fema…              15321            50272          30476.
## 8 Rural                Male               16285            52944          30759.
ggplot(severe_rate_region_sex, aes(x = urban_classification, y = severe_per_100k, fill = sex)) +
  geom_col(position = "dodge") +
  geom_text(
    aes(label = round(severe_per_100k, 1)),
    position = position_dodge(width = 0.9),
    vjust = -0.5,
    size = 3.5
  ) +
  labs(
    title = "Severe Cases per 100,000 Population by Region and Sex",
    x = "Region",
    y = "Severe Cases per 100,000 People",
    fill = "Sex"
  ) +
  theme_minimal()