## Warning: Found less unique colors (9) than unique zcol values (10)! 
## Interpolating color vector to match number of zcol values.
# Getting and loading required packages

if (!require("tidyverse"))
  install.packages("tidyverse")
if (!require("gtExtras"))
  install.packages("gtExtras")
if (!require("leafpop"))
  install.packages("leafpop")
if (!require("sf"))
  install.packages("sf")
if (!require("mapview"))
  install.packages("mapview")
if (!require("RColorBrewer"))
  install.packages("RColorBrewer")
if (!require("leaflet.extras2"))
  install.packages("leaflet.extras2")
if (!require("leafsync"))
  install.packages("leafsync")

library(tidyverse)
library(gtExtras)
library(sf)
library(mapview)
library(leafpop)
library(RColorBrewer)
library(leafsync)

# Reloading the rent data

FMR_RuCo <- read_csv("https://raw.githubusercontent.com/drkblake/Data/refs/heads/main/FMR_RuCo.csv")

# Showing the rent data

FMR_RuCo_table <- gt(FMR_RuCo) %>%
  tab_header("Rutherford FMR, by size and ZIP") %>%
  cols_align(align = "left") %>%
  gt_theme_538
FMR_RuCo_table

# Downloading the ZIP code map file

download.file(
  "https://www2.census.gov/geo/tiger/GENZ2020/shp/cb_2020_us_zcta520_500k.zip",
  "ZCTAs2020.zip"
  )

# Unzipping the ZIP code map file

unzip("ZCTAs2020.zip")

# Loading the ZIP code file into R as "ZCTAMap"

ZCTAMap <- read_sf("cb_2020_us_zcta520_500k.shp")

# Making ZIP a character variable

FMR_RuCo$ZIP <- as.character(FMR_RuCo$ZIP)

# Joining the files

FMR_RuCo_Map <- left_join(FMR_RuCo, ZCTAMap, by = c("ZIP" = "ZCTA5CE20"))

# Dropping unneeded columns

FMR_RuCo_Map <- FMR_RuCo_Map %>%
  select(-c(AFFGEOID20, GEOID20, NAME20, LSAD20, ALAND20, AWATER20))

# Converting FMR_RuCo_Map

FMR_RuCo_Map <- st_as_sf(FMR_RuCo_Map)

# Mapping by ZIP code

ZIP_Map <- mapview(
  FMR_RuCo_Map,
  zcol = "ZIP",
  layer.name = "ZIP code",
  popup = popupTable(
    FMR_RuCo_Map,
    feature.id = FALSE,
    row.numbers = FALSE,
    zcol = c("ZIP", "Studio", "BR1", "BR2", "BR3", "BR4")))

# Showing the map

ZIP_Map

# Mapping by ZIP_Average

Avg_Rent_Map <- mapview(
  FMR_RuCo_Map,
  zcol = "ZIP_Average",
  col.regions = brewer.pal(9, "Paired"),
  layer.name = "Average rent",
  popup = popupTable(
    FMR_RuCo_Map,
    feature.id = FALSE,
    row.numbers = FALSE,
    zcol = c("ZIP", "Studio", "BR1", "BR2", "BR3", "BR4")))

# Showing the map

Avg_Rent_Map

Rent_Category_Map <- mapview(
  FMR_RuCo_Map,
  zcol = "Rent_Category",
  col.regions = brewer.pal(8, "PuOr"),
  layer.name = "Rent category",
  popup = popupTable(
    FMR_RuCo_Map,
    feature.id = FALSE,
    row.numbers = FALSE,
    zcol = c("ZIP", "Studio", "BR1", "BR2", "BR3", "BR4")
  )
)

sync(Rent_Category_Map, Avg_Rent_Map)