# Installing required packages

if (!require("tidyverse")) install.packages("tidyverse")
## Loading required package: tidyverse
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6     ✔ purrr   0.3.4
## ✔ tibble  3.1.8     ✔ dplyr   1.0.9
## ✔ tidyr   1.2.0     ✔ stringr 1.4.0
## ✔ readr   2.1.2     ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
if (!require("tidycensus")) install.packages("tidycensus")
## Loading required package: tidycensus
if (!require("sf")) install.packages("sf")
## Loading required package: sf
## Warning: package 'sf' was built under R version 4.2.2
## Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
if (!require("mapview")) install.packages("mapview")
## Loading required package: mapview
## Warning: package 'mapview' was built under R version 4.2.2
library(tidycensus)
library(tidyverse)
library(sf)
library(mapview)
options(tigris_use_cache = TRUE)

# NOTE: Obtain a Census API key from 
# https://api.census.gov/data/key_signup.html
# and replace the census_api_key code line's 
# PastYourAPIKeyBetwenTheseQuoteMarks text with your
# API key. Also, delete the "#" from the front of the 
# census_api_key code.

#census_api_key("PasteYourAPIKeyBetwenTheseQuoteMarks")

# Getting ACS variable info
# Change "2021" to your preferred year.
# Change "acs1" to "acs5" if you want five-year data.

DetailedTables <- load_variables(2021, "acs5", cache = TRUE)
SubjectTables <- load_variables(2021, "acs5/subject", cache = TRUE)
ProfileTables <- load_variables(2021, "acs5/profile", cache = TRUE)
SubjectTables$geography <- "NA"
ProfileTables$geography <- "NA"
AllVariables <- rbind(DetailedTables,SubjectTables,ProfileTables)
rm(DetailedTables,SubjectTables,ProfileTables)

# When you have the name of the variable you want, paste it 
# in place of "B01001_001" in both instances below.
# Replace "TN" with a different two-letter state
# abbreviation to get data for that state's counties.

# Getting the map data
MapData <- get_acs(geography = "tract",
                   state = "TN",
                   county = "Rutherford",
                   variables = c(Pop = "B01001_001",
                                 Age = "B01002_001",
                                 AgeMale = "B01002_002",
                                 AgeFemale = "B01002_003",
                                 White = "DP05_0037P",
                                 Black = "DP05_0038P",
                                 College = "DP02_0068P",
                                 HHIncome = "S1903_C03_001",
                                 PctMale = "DP05_0002P",
                                 PctUninsured = "DP03_0099P",
                                 PctBroadband = "DP02_0154P",
                                 PctBilingual = "DP02_0114P",
                                 PctSNAP = "S2201_C04_001"),
                   year = 2021,
                   survey = "acs5",
                   output = "wide",
                   geometry = TRUE)
## Getting data from the 2017-2021 5-year ACS
## Fetching data by table type ("B/C", "S", "DP") and combining the result.
#Pruning any empty columns
MapData <- MapData[colSums(!is.na(MapData)) > 0]

# Making preview maps
options(scipen=999)

mapview(MapData,zcol = "PopE",
        layer.name = "Population count",
        popup = FALSE)
mapview(MapData,zcol = "AgeE",
        layer.name = "Median age",
        popup = FALSE)
mapview(MapData,zcol = "AgeMaleE",
        layer.name = "Male median age",
        popup = FALSE)
mapview(MapData,zcol = "AgeFemaleE",
        layer.name = "Female median age",
        popup = FALSE)
mapview(MapData,zcol = "HHIncomeE",
        layer.name = "Median household income",
        popup = FALSE)
mapview(MapData,zcol = "WhiteE",
        layer.name = "Pct. white",
        popup = FALSE)
mapview(MapData,zcol = "BlackE",
        layer.name = "Pct. Black",        popup = FALSE)
mapview(MapData,zcol = "CollegeE",
        layer.name = "Pct. college degree",        
        popup = FALSE)
mapview(MapData,zcol = "PctMaleE",
        layer.name = "Pct. Male",
        popup = FALSE)
mapview(MapData,zcol = "PctUninsuredE",
        layer.name = "Pct. no health insurance",
        popup = FALSE)
mapview(MapData,zcol = "PctBroadbandE",
        layer.name = "Pct. broadband",
        popup = FALSE)
mapview(MapData,zcol = "PctBilingualE",
        layer.name = "Pct. non-English at home",
        popup = FALSE)
mapview(MapData,zcol = "PctSNAPE",
        layer.name = "Pct. SNAP",
        popup = FALSE)
# The code below will export a .kml and .csv file
# to your computer's hard drive. Look for the files
# in the same subdirectory as this R script. Columns
# containing only "NA"codes will be deleted.

#Making a .kml Map File
st_write(MapData,"MapData.kml", append = FALSE)
## Writing layer `MapData' to data source `MapData.kml' using driver `KML'
## Writing 64 features with 28 fields and geometry type Multi Polygon.
#Making a CSV data file
CSVData <- st_drop_geometry(MapData)
write.csv(CSVData,"CSVData.csv", row.names = FALSE)