Load the libraries and set the working directory

library(tidyverse)
library(tidyr)
library(ggplot2)
library(maps)
setwd("/Users/xutongzhang/Desktop")
cities500 <- read_csv("500CitiesLocalHealthIndicators.cdc.csv")

The GeoLocation variable has (lat, long) format

Split GeoLocation (lat, long) into two columns: lat and long

latlong <- tidyr::extract(cities500, GeoLocation, c('lat', 'long'), 
               regex = ',?\\s*\\((\\d+\\.\\d+).*(-?\\d+\\.\\d+)\\)')
head(latlong)
## # A tibble: 6 × 25
##    Year StateAbbr StateDesc  CityName  GeographicLevel DataSource Category      
##   <dbl> <chr>     <chr>      <chr>     <chr>           <chr>      <chr>         
## 1  2017 CA        California Hawthorne Census Tract    BRFSS      Health Outcom…
## 2  2017 CA        California Hawthorne City            BRFSS      Unhealthy Beh…
## 3  2017 CA        California Hayward   City            BRFSS      Health Outcom…
## 4  2017 CA        California Hayward   City            BRFSS      Unhealthy Beh…
## 5  2017 CA        California Hemet     City            BRFSS      Prevention    
## 6  2017 CA        California Indio     Census Tract    BRFSS      Health Outcom…
## # ℹ 18 more variables: UniqueID <chr>, Measure <chr>, Data_Value_Unit <chr>,
## #   DataValueTypeID <chr>, Data_Value_Type <chr>, Data_Value <dbl>,
## #   Low_Confidence_Limit <dbl>, High_Confidence_Limit <dbl>,
## #   Data_Value_Footnote_Symbol <chr>, Data_Value_Footnote <chr>,
## #   PopulationCount <dbl>, lat <chr>, long <chr>, CategoryID <chr>,
## #   MeasureId <chr>, CityFIPS <dbl>, TractFIPS <dbl>, Short_Question_Text <chr>

Filter the dataset

Remove the StateDesc that includes the United Sates, select Prevention as the category (of interest), filter for only measuring crude prevalence and select only 2017.

latlong_clean <- latlong |>
  filter(StateDesc != "United States") |>
  filter(Category == "Prevention") |>
  filter(Data_Value_Type == "Crude prevalence") |>
  filter(Year == 2017)
head(latlong_clean)
## # A tibble: 6 × 25
##    Year StateAbbr StateDesc  CityName   GeographicLevel DataSource Category  
##   <dbl> <chr>     <chr>      <chr>      <chr>           <chr>      <chr>     
## 1  2017 AL        Alabama    Montgomery City            BRFSS      Prevention
## 2  2017 CA        California Concord    City            BRFSS      Prevention
## 3  2017 CA        California Concord    City            BRFSS      Prevention
## 4  2017 CA        California Fontana    City            BRFSS      Prevention
## 5  2017 CA        California Richmond   Census Tract    BRFSS      Prevention
## 6  2017 FL        Florida    Davie      Census Tract    BRFSS      Prevention
## # ℹ 18 more variables: UniqueID <chr>, Measure <chr>, Data_Value_Unit <chr>,
## #   DataValueTypeID <chr>, Data_Value_Type <chr>, Data_Value <dbl>,
## #   Low_Confidence_Limit <dbl>, High_Confidence_Limit <dbl>,
## #   Data_Value_Footnote_Symbol <chr>, Data_Value_Footnote <chr>,
## #   PopulationCount <dbl>, lat <chr>, long <chr>, CategoryID <chr>,
## #   MeasureId <chr>, CityFIPS <dbl>, TractFIPS <dbl>, Short_Question_Text <chr>

What variables are included? (can any of them be removed?)

names(latlong_clean)
##  [1] "Year"                       "StateAbbr"                 
##  [3] "StateDesc"                  "CityName"                  
##  [5] "GeographicLevel"            "DataSource"                
##  [7] "Category"                   "UniqueID"                  
##  [9] "Measure"                    "Data_Value_Unit"           
## [11] "DataValueTypeID"            "Data_Value_Type"           
## [13] "Data_Value"                 "Low_Confidence_Limit"      
## [15] "High_Confidence_Limit"      "Data_Value_Footnote_Symbol"
## [17] "Data_Value_Footnote"        "PopulationCount"           
## [19] "lat"                        "long"                      
## [21] "CategoryID"                 "MeasureId"                 
## [23] "CityFIPS"                   "TractFIPS"                 
## [25] "Short_Question_Text"

Remove the variables that will not be used in the assignment

prevention <- latlong_clean |>
  select(-DataSource,-Data_Value_Unit, -DataValueTypeID, -Low_Confidence_Limit, -High_Confidence_Limit, -Data_Value_Footnote_Symbol, -Data_Value_Footnote)
head(prevention)
## # A tibble: 6 × 18
##    Year StateAbbr StateDesc  CityName  GeographicLevel Category UniqueID Measure
##   <dbl> <chr>     <chr>      <chr>     <chr>           <chr>    <chr>    <chr>  
## 1  2017 AL        Alabama    Montgome… City            Prevent… 151000   Choles…
## 2  2017 CA        California Concord   City            Prevent… 616000   Visits…
## 3  2017 CA        California Concord   City            Prevent… 616000   Choles…
## 4  2017 CA        California Fontana   City            Prevent… 624680   Visits…
## 5  2017 CA        California Richmond  Census Tract    Prevent… 0660620… Choles…
## 6  2017 FL        Florida    Davie     Census Tract    Prevent… 1216475… Choles…
## # ℹ 10 more variables: Data_Value_Type <chr>, Data_Value <dbl>,
## #   PopulationCount <dbl>, lat <chr>, long <chr>, CategoryID <chr>,
## #   MeasureId <chr>, CityFIPS <dbl>, TractFIPS <dbl>, Short_Question_Text <chr>

The new dataset “Prevention” is a manageable dataset now.

For your assignment, work with the cleaned “Prevention” dataset

1. Once you run the above code, filter this dataset one more time for any particular subset.

Filter chunk here

# Filter "Cholesterol screening"
cholesterol_screening_subset <- prevention |>
  filter(Measure == "Cholesterol screening among adults aged >=18 Years")

2. Based on the GIS tutorial (Japan earthquakes), create one plot about something in your subsetted dataset.

First plot chunk here

# Create a scatter plot for cholesterol screening rates by city
ggplot(cholesterol_screening_subset, aes(x = long, y = lat, color = Data_Value)) +
  geom_point() +
  labs(title = "Cholesterol Screening Prevalence by City",
       x = "Longitude",
       y = "Latitude",
       color = "Prevalence Rate (%)") +
  theme_minimal()

3. Now create a map of your subsetted dataset.

First map chunk here

# Data cleaning and processing
cholesterol_screening_subset$long <- as.numeric(cholesterol_screening_subset$long)
cholesterol_screening_subset$lat <- as.numeric(cholesterol_screening_subset$lat)
cholesterol_screening_subset <- na.omit(cholesterol_screening_subset)

# Set up the base map layer
world_map <- map_data("world")

# Create the ggplot
ggplot() +
  # Base map layer
  geom_polygon(
    data = world_map, 
    aes(x = long, y = lat, group = group), 
    fill = "lightgrey", 
    color = "white"
  ) +
  # Data points layer
  geom_point(
    data = cholesterol_screening_subset, 
    aes(x = long, y = lat, color = Data_Value), 
    size = 2
  ) +
  # Color gradient
  scale_color_gradient(low = "blue", high = "red") +
  # Labels
  labs(
    title = "Map of Cholesterol Screening Prevalence",
    x = "Longitude", 
    y = "Latitude",
    color = "Prevalence Rate (%)"
  ) +
  # Setting the limits
  xlim(
    min(cholesterol_screening_subset$long, na.rm = TRUE) - 5, 
    max(cholesterol_screening_subset$long, na.rm = TRUE) + 5
  ) +
  ylim(
    min(cholesterol_screening_subset$lat, na.rm = TRUE) - 5, 
    max(cholesterol_screening_subset$lat, na.rm = TRUE) + 5
  ) +
  # Themes and aesthetics
  theme_minimal() +
  theme(legend.position = "bottom") +
  coord_fixed(1.3)

4. Refine your map to include a mousover tooltip

Refined map chunk here

library(leaflet)

# Assuming cholesterol_screening_subset is your data frame and it has 'lat', 'long', and 'Data_Value' columns
# Convert the columns to numeric if they're not already
cholesterol_screening_subset$lat <- as.numeric(cholesterol_screening_subset$lat)
cholesterol_screening_subset$long <- as.numeric(cholesterol_screening_subset$long)

# Create a leaflet map
leaflet(data = cholesterol_screening_subset) %>%
  addTiles() %>%  # Add the default OpenStreetMap map tiles
  addCircles(
    lng = ~long, lat = ~lat, weight = 1,
    radius = 500,
    color = ~colorNumeric(palette = "viridis", domain = cholesterol_screening_subset$Data_Value)(Data_Value),
    label = ~paste("Prevalence Rate:", Data_Value, "%"),
    popup = ~paste("City:", CityName, "<br>",
                   "Prevalence Rate:", Data_Value, "%")
  ) %>%
  addLegend(
    "bottomright",
    pal = colorNumeric(palette = "viridis", domain = cholesterol_screening_subset$Data_Value),
    values = ~Data_Value,
    title = "Prevalence Rate",
    labFormat = labelFormat(suffix = "%")
  )

5. Write a paragraph

In a paragraph, describe the plots you created and what they show.

The static map and interactive map we generated from the “Prevention” dataset show cholesterol screening rates across various locales. The static map uses a color gradient to indicate screening prevalence, with the intensity of color reflecting higher or lower rates. The interactive map, made with leaflet, adds functionality: clicking on a city shows a popup with the city name and its screening rate. Both visuals are practical for identifying areas with different levels of cholesterol health interventions, making it easier to target areas for improvement in public health initiatives.