Project Milestone 4
Milestone #4 Objective
Visualizations complete.
Milestone #4 Details
Please submit an Rmd or Qmd and publish an html file on RPubs with the following:
Final datasets for creation of visualization
Join all datasets together
Calculate any remaining data elements needed for analysis
Show code used to create joined dataset, but please do not print full data frame output (showing data structure with
str()is okay)
Visualizations (at least one per group member)
One print quality table as requested in scenario
One print quality plot or chart as requested in scenario
For groups of 3, one additional print quality table or plot of your choice (can support the requested data in the scenario, or answer a different question using the same data sources)
For each visual, include
Code used to generate visual
Legend (if necessary)
1-2 sentence interpretation
NOTE:
Please make sure the visual can stand-alone, meaning it includes enough information in title, legend, and footnote so that a person who sees only the visualization could understand what is being presented.
Please also make sure column names, axis labels, and any other labels are meaningful and not just the name of the variable (ex: “County” rather than “county_name”)
Html file that is professionally prepared for presentation and published to RPubs
Only the necessary information is in the output (e.g., suppress entire data frame outputs but showing data structure with
str()is okay.Code used to import and clean data (milestones 2 and 3) can be included in the rmd/qmd but please use the option include=FALSE in order to prevent the code and any output from. Code chunk would look like
{r chunk_name, include=FALSE}Utilize
warning=FALSEandmessage=FALSEto suppress any warnings/messages that may be displaying from any chunksFor this milestone please make sure code for visualizations are included in the final file. Show your work by “echoing” code used in Rmd/Qmd file to create your tables and graphs. ```{r, echo = TRUE} in code chunk preferences.
Use headers and sub headers to create an organized document
Make sure you commit and push your rsconnect folder!
```{r, include=FALSE} #Relevant Libraries or Tools Needed
library(tidyverse) library(janitor) library(readr)
# Datasets:
## ca_pop_23
```{r, include=FALSE}
#import current datasets and format as in milestone 2
ca_pop_23 <- read_csv("../data/ca_pop_2023.csv",
na = c("", " ", "NA", "N/A", "Unknown"),
col_types = cols(
age_cat = col_character(),
sex = col_character(),
county = col_character(),
race7 = col_character()
)
) %>%
clean_names() %>%
rename(race_eth = race7) %>%
mutate(race_eth = case_when(
race_eth == "WhiteTE NH" ~ "White, Non-Hispanic",
race_eth == "Black NH" ~ "Black, Non-Hispanic",
race_eth == "AIAN NH" ~ "American Indian or Alaska Native, Non-Hispanic",
race_eth == "Asian NH" ~ "Asian, Non-Hispanic",
race_eth == "NHPI NH" ~ "Native Hawaiian or Pacific Islander, Non-Hispanic",
race_eth == "MR NH" ~ "Multiracial (two or more of above races), Non-Hispanic",
race_eth == "Hispanic" ~ "Hispanic (any race)")) %>%
mutate(age_cat = case_when(
age_cat == "0-4" ~ "0-17",
age_cat == "5-11" ~ "0-17",
age_cat == "12-17" ~ "0-17",
TRUE ~ age_cat))
sim_CA
{r, include=FALSE} sim_CA <- read_csv("../data/sim_novelid_CA.csv", na = c("", " ", "NA", "N/A", "Unknown"), col_types = cols( age_cat = col_character(), sex = col_character(), county = col_character(), race_ethnicity = col_double(), dt_diagnosis = col_date() ) ) %>% clean_names() %>% rename(race_eth = race_ethnicity, dx_date = dt_diagnosis) %>% mutate(race_eth = case_when( race_eth == 1 ~ "White, Non-Hispanic", race_eth == 2 ~ "Black, Non-Hispanic", race_eth == 3 ~ "American Indian or Alaska Native, Non-Hispanic", race_eth == 4 ~ "Asian, Non-Hispanic", race_eth == 5 ~ "Native Hawaiian or Pacific Islander, Non-Hispanic", race_eth == 6 ~ "Multiracial (two or more of above races), Non-Hispanic", race_eth == 7 ~ "Hispanic (any race)", race_eth == 9 ~ NA ))
sim_LA
{r, include=FALSE} sim_LA <- read_csv("../data/sim_novelid_LACounty.csv", na = c("", " ", "NA", "N/A", "Unknown"), col_types = cols( AGE_CATEGORY = col_character(), SEX = col_character(), RACE_ETH = col_character(), DT_DX = col_character() ) ) %>% clean_names() %>% rename(age_cat = age_category, dx_date = dt_dx, new_infections = dx_new, cumulative_infected = infected_cumulative, new_severe = severe_new, cumulative_severe = severe_cumulative, new_unrecovered = unrecovered_new, cumulative_unrecovered = unrecovered_cumulative) %>% mutate(dx_date = as.Date(dx_date, format = "%d%b%Y"), county = "Los Angeles County") %>% select(-dt_report)
combining datasets
{r, include=FALSE} sim_bind <- bind_rows(sim_CA, sim_LA)
aggregating the data from demographic and geographic strata (s) of interest
```{r, echo=TRUE, warning=FALSE, message=FALSE} #county + age_cat + sex + race_eth
sim_aggregate <- sim_bind %>% group_by(county, age_cat, sex, race_eth) %>% summarise(total_infections = sum(new_infections, na.rm = TRUE), total_severe = sum(new_severe, na.rm = TRUE), total_unrecovered = sum(new_unrecovered, na.rm = TRUE), .groups = “drop”)
glimpse(sim_aggregate)
## aggregating the data from demographic and geographic stata (s) of interest ##from population data
```{r, echo=TRUE, warning=FALSE, message=FALSE}
pop_aggregate <- ca_pop_23 %>%
group_by(county, age_cat, sex, race_eth) %>%
summarise(pop = sum(pop, na.rm = TRUE),
.groups = "drop")
#new variable
#standardize county names in pop aggregate data so that it can join other data
pop_aggregate <- pop_aggregate %>%
mutate(county = paste(county, "County"))
#joining sim agg data to pop agg data
joined_agg <- sim_aggregate %>%
left_join(pop_aggregate,
by = c("county", "age_cat", "sex", "race_eth"))
#new variable
#infection rate
joined_agg <- joined_agg %>%
mutate(infection_rate = if_else(pop > 0,
(total_infections / pop) * 100000,
NA_real_))
#Heatmap visualizer
```{r, echo=TRUE, warning=FALSE, message=FALSE} joined_heat <- joined_agg %>% group_by(age_cat, race_eth) %>% summarise(total_infections = sum(total_infections, na.rm = TRUE), total_population = sum(pop[pop > 0], na.rm = TRUE), .groups = “drop”) %>% mutate(infection_rate = (total_infections / total_population) * 100000)
ggplot(joined_heat, aes(x = age_cat, y = race_eth, fill = infection_rate)) + geom_tile(color = “white”) + scale_fill_gradient(low = “lightblue”, high = “darkblue”) + labs(title = “Infection Rates by Age and Race/Ethnicity”, subtitle = “California, infections per 100,000 population”, x = “Age Group”, y = “Race/Ethnicity”, fill = “Rate per 100,000”) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1), axis.text.y = element_text(size = 8))
**Interpretation:** This heat map colors the differences in infection rates across age and racial/ethnic groups in California. Adults aged 65 and older experienced the highest infection rates across racial and ethnic groups, with notably high rates among American Indian or Alaska Native, Hispanic and White, non-Hispanic populations. Adults aged 18–49 were also observed to have relatively high infection rates, while individuals aged 0–17 consistently had lower rates. These rates suggest that the outbreak varied across demographic populations, with older adults experiencing particularly high infection rates. Public health prevention efforts should prioritize older adults and consider culturally appropriate outreach and improve access to prevention and treatment services for populations experiencing higher infection rates.
## Aggregate Summary by Race
```{r,echo=TRUE, warning=FALSE, message=FALSE}
race_aggregation <- joined_agg %>%
group_by(race_eth) %>%
summarise(
total_infections = sum(total_infections, na.rm = TRUE),
total_severe = sum(total_severe, na.rm = TRUE),
total_unrecovered = sum(total_unrecovered, na.rm = TRUE),
total_population = sum(pop, na.rm = TRUE),
# infection rate calc
infection_rate_100k = (sum(total_infections, na.rm = TRUE) / sum(pop, na.rm = TRUE)) * 100000,
.groups = "drop"
)
#view aggregated data
print(race_aggregation)
California Heat Map
```{r,echo=TRUE, warning=FALSE, message=FALSE}
#install.packages(c(“leaflet”, “sf”, “tigris”, “tidyverse”))
#library(tidyverse) library(leaflet) library(sf) library(tigris)
county_data <- joined_agg %>% group_by(county) %>% summarise(total_infections = sum(total_infections, na.rm = TRUE), total_severe = sum(total_severe, na.rm = TRUE), total_unrecovered = sum(total_unrecovered, na.rm = TRUE), pop = sum(pop, na.rm = TRUE)) %>% mutate(infection_rate = (total_infections / pop) * 100000)
ca_counties <- counties( state = “CA”, cb = TRUE, year = 2023)
ca_counties <- ca_counties %>% mutate(county = NAMELSAD)
ca_map <- ca_counties %>% left_join(county_data, by = “county”)
ca_map %>% st_drop_geometry() %>% select(county, total_infections, infection_rate) %>% head()
pal <- colorNumeric( palette = “YlOrRd”, domain = ca_map$infection_rate)
map <- leaflet(ca_map) %>% addControl( html = “California County Infection Rates
“, position =”topleft” ) %>% addPolygons( fillColor = ~pal(infection_rate), weight = 1, color = “white”, fillOpacity = 0.8, label = ~paste0( county, “:”, round(infection_rate, 1), ” infections per 100,000”), popup = ~paste0( “”, county, “
”, “Total infections:”, format(total_infections, big.mark = “,”), “
”, “Severe cases:”, format(total_severe, big.mark = “,”), “
”, “Population:”, format(pop, big.mark = “,”), “
”, “Infection rate:”, round(infection_rate, 1), ” per 100,000”), highlightOptions = highlightOptions( weight = 3, color = “black”, bringToFront = TRUE)) %>% addLegend( pal = pal, values = ~infection_rate, title = “Infection Rate
per 100,000”, position = “bottomright”)
map
**Interpretation:** This California county heat map uses color to display geographic differences in infection rates across the state. Imperial County experienced the highest infection rate, with approximately 43,767 infections per 100,000 population, followed by Inyo County (26,891), Kern County (24,193), Tulare County (23,694), and Kings County (22,844). We can see that the outbreak did not affect all geographic populations equally. Public health prevention and treatment resources should prioritize counties with elevated infection rates through targeted prevention efforts, expanded testing and improve access to treatment services.
## Epi Curve
```{r, echo=TRUE, warning=FALSE, message=FALSE}
age_levels <- unique(na.omit(sim_bind$age_cat))
age_levels <- age_levels[order(readr::parse_number(age_levels))]
epi_curve <- sim_bind %>%
filter(!is.na(dx_date), !is.na(age_cat)) %>%
mutate(week = lubridate::floor_date(dx_date, "week"),
age_cat = factor(age_cat, levels = age_levels)) %>%
group_by(week, age_cat) %>%
summarise(new_infections = sum(new_infections, na.rm = TRUE), .groups = "drop")
ggplot(epi_curve, aes(x = week, y = new_infections, fill = age_cat)) +
geom_col(width = 6) +
scale_fill_brewer(palette = "YlGnBu") +
scale_y_continuous(labels = scales::comma,
expand = expansion(mult = c(0, 0.05))) +
scale_x_date(date_labels = "%b %Y", date_breaks = "2 months") +
labs(title = "Weekly New Infections of a Novel Respiratory Disease by Age Group, California",
subtitle = "Statewide (all counties including Los Angeles County); each bar is one week, stacked by age group",
x = "Week of Diagnosis",
y = "Number of New Infections per Week",
fill = "Age Group (years)",
caption = "Source: Simulated CDPH surveillance data. Weeks begin on Sunday; counts are by date of diagnosis.\nRecords with missing diagnosis date or age group are excluded.") +
theme_minimal(base_size = 13) +
theme(legend.position = "bottom",
plot.title = element_text(face = "bold"),
plot.caption = element_text(hjust = 0, size = 9),
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.minor = element_blank())
interpretation: Statewide weekly new infections began rising in August 2023, increasing drastically in September, and peaking between 390,000 to 400,000 new infections per week by late September and early October. Number of cases stayed above 300,000 per week through October, quickly decreasing in November and reaching nearly zero by December. Adults between the ages of 18 to 49 accounted for the largest share of cases in every week, followed by adults 65 and older, while children and teens (0-17) accounted for the fewest amount of new cases per week.
Comparison of Infection Rates by Race and Region of Residence
```{r,include=FALSE}
library(dplyr) library(ggplot2) library(stringr) library(scales)
Define California Counties by North, Central, South
north_counties <- c( “Alameda”, “Butte”, “Colusa”, “Contra Costa”, “Del Norte”, “El Dorado”, “Glenn”, “Humboldt”, “Lake”, “Lassen”, “Marin”, “Mendocino”, “Modoc”, “Napa”, “Nevada”, “Placer”, “Plumas”, “Sacramento”, “San Francisco”, “San Mateo”, “Santa Clara”, “Shasta”, “Sierra”, “Siskiyou”, “Solano”, “Sonoma”, “Sutter”, “Tehama”, “Trinity”, “Yolo”, “Yuba” )
central_counties <- c( “Alpine”, “Amador”, “Calaveras”, “Fresno”, “Inyo”, “Kern”, “Kings”, “Madera”, “Mariposa”, “Merced”, “Mono”, “Monterey”, “San Benito”, “San Joaquin”, “San Luis Obispo”, “Santa Cruz”, “Stanislaus”, “Tulare”, “Tuolumne” )
south_counties <- c( “Imperial”, “Los Angeles”, “Orange”, “Riverside”, “San Bernardino”, “San Diego”, “Santa Barbara”, “Ventura” )
Clean county names
region_race_summary <- joined_agg %>% mutate( county_clean = str_remove(county, “\s+County$”), region = case_when( county_clean %in% north_counties ~ “North”, county_clean %in% central_counties ~ “Central”, county_clean %in% south_counties ~ “South”, TRUE ~ NA_character_ ) ) %>% filter( !is.na(region), !race_eth %in% c(“All”, “Total”, “Unknown”) ) %>% group_by(region, race_eth) %>% summarise( infections = sum(total_infections, na.rm = TRUE), severe = sum(total_severe, na.rm = TRUE), unrecovered = sum(total_unrecovered, na.rm = TRUE), population = sum(pop, na.rm = TRUE), calc_rate_100k = (infections / population) * 100000, .groups = “drop” ) %>% mutate(region = factor(region, levels = c(“North”, “Central”, “South”)))
```{r,echo=TRUE, warning=FALSE, message=FALSE}
format_region_plain <- function(label, counties, wrap_width = 110) {
text <- paste0(label, " (", length(counties), "): ", paste(counties, collapse = ", "), ".")
str_wrap(text, width = wrap_width, exdent = 4)
}
region_caption <- region_caption <- paste(
format_region_plain("NORTH", north_counties),
format_region_plain("CENTRAL", central_counties),
format_region_plain("SOUTH", south_counties),
sep = "\n"
)
ggplot(region_race_summary, aes(x = reorder(race_eth, calc_rate_100k), y = calc_rate_100k, fill = region)) +
geom_col(position = position_dodge(width = 0.8), width = 0.72) +
coord_flip() +
scale_y_continuous(labels = comma, expand = expansion(mult = c(0, 0.08))) +
scale_fill_manual(
values = c("North" = "#2b5c8f", "Central" = "#d95f02", "South" = "#1b9e77"),
name = "Region"
) +
labs(
title = "Infection Rate per 100,000 by Race/Ethnicity and Region in California",
subtitle = "Aggregated across all counties, age groups, and sexes",
x = NULL,
y = "Infection Rate (per 100,000)",
caption = region_caption
) +
theme_minimal(base_size = 12) +
theme(
legend.position = "top",
panel.grid.major.y = element_blank(),
plot.title = element_text(face = "bold")
)
###Interpretation
When looking at infection rate stratified by race and Californian region Central California demonstrates a higher rate for all races when compared to both Northern and Southern regions of California.
Data Dictionary
#data dictionary
#category descriptions
descriptions <- c(
county = "County of residence",
age_cat = "Age Category",
sex = "Sex categorization defined by California Department of Finance",
race_eth = "Race-ethnicity categorizatioon as defined by California Department of Finance.",
total_infections = "Cumulative historical count infections.",
total_severe = "Total number of individuals with severe disease requiring hospitalization.",
total_unrecovered = "Total number of people reported as unrecovered after a week of being diagnosed.",
pop = "Total population",
infection_rate = "Calculated rate of infection per 100,000 population."
)
#dictionary coding
data_dictionary <- data.frame(
Variable_Name = colnames(joined_agg),
Data_Type = sapply(joined_agg, function(x) paste(class(x), collapse = ", ")),
Description = unname(descriptions[colnames(joined_agg)]),
row.names = NULL,
stringsAsFactors = FALSE
)
print(data_dictionary)
Descriptive Statistics Table
joined_agg %>%
select(total_infections, total_severe, pop, infection_rate) %>%
summary()