Load R Packages

library(openxlsx)
library(tidyverse)
library(data.table)
library(stringi)
library(pander)
library(psych)

Individuals with Person and Place Characteristics

indiv <- readRDS("indiv.rds")
head(indiv) %>%
  kbl() %>%
  kable_paper(full_width = FALSE)
PID Gender GEOID CTract cen_long cen_lat
1 M 12071000700 700 -81.87042 26.63124
2 M 34001001100 1100 -74.43150 39.36434
3 M 36005001900 1900 -73.91160 40.80433
4 M 36005001900 1900 -73.91160 40.80433
5 M 36005002500 2500 -73.91855 40.80727
6 F 36005002702 2702 -73.91396 40.80654

Obtain Geometry of Census Tracts in the NYC Area

nyc_tracts <- tracts(state = '36', county = c('061','047','081','005','085','059','119'))

A Map of NYC with a Single Location Marked

leaflet(nyc_tracts) %>%
  addTiles() %>% 
  addCircleMarkers(~-73.9973, ~40.7308, radius = 5, color = "green") %>%
  setView(-73.8740, 40.7769, zoom = 11.45)

Pull Four Variables from the Most Recent American Community Survey (ACS)

nyc_struc <- get_acs(geography = "tract", 
                     variables = c("B06009_001", "B06009_002",
                                   "B17001_001", "B17001_002"), 
                     state = "36",
                     county = c("005","047","061","081","085","059","119"),
                     geometry = TRUE,
                     output = "wide") %>% 
mutate(pct_poverty = B17001_002E/B17001_001E,
       pct_noHS = B06009_002E / B06009_001E)

nyc_struc$CTract <- as.numeric(substr(nyc_struc$GEOID, 6, 11))

nyc_struc <- na.omit(nyc_struc)

Map Showing Proportion of Adults without High School Diploma by Census Tract (All of NYC)

pal <- colorNumeric(palette = "viridis", 
                    domain = nyc_struc$pct_noHS)

nyc_struc %>%
    st_transform(crs = "+init=epsg:4326") %>%
    leaflet(width = "100%") %>%
    addProviderTiles(provider = "CartoDB.Positron") %>%
    addPolygons(popup = ~ str_extract(NAME, "^([^,]*)"),
                stroke = FALSE,
                smoothFactor = 0,
                fillOpacity = 0.7,
                color = ~ pal(pct_noHS)) %>%
    addLegend("bottomright", 
              pal = pal, 
              values = ~ pct_noHS,
              title = "No High School Diploma",
              opacity = 1)

Merge Data on People, Their Chacteristics and Locations with Census Tract and Geographic Data

nyc_struc <- merge(nyc_struc, indiv, by = c("GEOID", "CTract"))

nyc_struc$Gender <- factor(nyc_struc$Gender)

A Map of NYC with Many Locations Marked

leaflet(nyc_struc) %>%
  addTiles() %>%
  addCircleMarkers(~cen_long, ~cen_lat, radius = 1, 
                   color = ~ifelse(Gender == "M", "navy", "red"), fillOpacity = 0.5) %>%
  addCircleMarkers(~-73.9973, ~40.7308, radius = 5, color = "green") %>%
  setView(-73.8740, 40.7769, zoom = 11.45)