# Installing and loading required packages

if (!require("tidyverse")) install.packages("tidyverse")
## Loading required package: tidyverse
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
if (!require("tidycensus")) install.packages("tidycensus")
## Loading required package: tidycensus
if (!require("sf")) install.packages("sf")
## Loading required package: sf
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
if (!require("mapview")) install.packages("mapview")
## Loading required package: mapview
library(tidyverse)
library(tidycensus)
library(sf)
library(mapview)

# Transmitting API key

census_api_key("f47d2ea953fa8297dad3dc44e5ac87f39e113b79")
## To install your API key for use in future sessions, run this function with `install = TRUE`.
# Fetching ACS codebooks

DetailedTables <- load_variables(2022, "acs5", cache = TRUE)
SubjectTables <- load_variables(2022, "acs5/subject", cache = TRUE)
ProfileTables <- load_variables(2022, "acs5/profile", cache = TRUE)

# Double checking target variables

ChosenVars <- filter(ProfileTables,name == "DP04_0063P"|
                       name == "DP02_0001")
print(ChosenVars$name)
## [1] "DP02_0001"  "DP04_0063P"
print(ChosenVars$label)
## [1] "Estimate!!HOUSEHOLDS BY TYPE!!Total households"                  
## [2] "Percent!!HOUSE HEATING FUEL!!Occupied housing units!!Utility gas"
print(ChosenVars$concept)
## [1] "Selected Social Characteristics in the United States"
## [2] "Selected Housing Characteristics"
# Specifying target variables

VariableList = 
  c(PctGasHeat_ = "DP04_0063P",
    Households_ = "DP02_0001")

# Fetching data

mydata <- get_acs(
  geography = "county",
  state = "TN",
  variables = VariableList,
  year = 2022,
  survey = "acs5",
  output = "wide",
  geometry = TRUE)
## Getting data from the 2018-2022 5-year ACS
## Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
## Using the ACS Data Profile
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |                                                                      |   1%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
# Reformatting data

mydata <-
  separate_wider_delim(mydata,
                       NAME,
                       delim = ", ",
                       names = c("County", "State"))
# Filtering data

filtereddata <- mydata %>% 
  filter(County == "Davidson County"|
           County == "Rutherford County"|
           County == "Williamson County"|
           County == "Cheatham County"|
           County == "Robertson County"|
           County == "Sumner County"|
           County == "Wilson County")

#Plotting data

ggplot(filtereddata, aes(x = PctGasHeat_E, y = reorder(County, PctGasHeat_E))) + 
  geom_errorbarh(aes(xmin = PctGasHeat_E - PctGasHeat_M, xmax = PctGasHeat_E + PctGasHeat_M)) + 
  geom_point(size = 3, color = "darkblue") + 
  theme_minimal(base_size = 12.5) + 
  labs(title = "Pct. households with gas heat", 
       subtitle = "Nashville-area counties. Brackets show error margins.", 
       x = "2018-2022 ACS estimate", 
       y = "")

#Mapping data

mapdata <- filtereddata %>% 
  rename(PctGasHeat = PctGasHeat_E,
         Households = Households_E)

mapdata <- st_as_sf(mapdata)

mapviewOptions(basemaps.color.shuffle = FALSE)
mapview(mapdata, zcol = "PctGasHeat",
        layer.name = "Pct. with gas heat",
        popup = TRUE)
#Better map

#Installing and activating some additional packages

if (!require("leaflet")) install.packages("leaflet")
## Loading required package: leaflet
if (!require("leaflet.extras2")) install.packages("leaflet.extras2")
## Loading required package: leaflet.extras2
library(leaflet)
library(leaflet.extras2)
library(leafpop)

# Defining a custome color palette for the map

mypalette = colorRampPalette(c('lightgray', 'darkorange'))

# Generating the map

mapview(mapdata, zcol = "PctGasHeat",
        col.regions = mypalette, at = seq(10, 60, 10),
        layer.name = "Pct. gas heat",
        popup = popupTable(mapdata,
                           feature.id = FALSE,
                           row.numbers = FALSE,
                           zcol = c("County",
                                    "State",
                                    "PctGasHeat",
                                    "Households")))
#Exporting data in .csv format

CSVdata <- st_drop_geometry(mapdata)
write.csv(CSVdata, "mydata.csv", row.names = FALSE)