# Load libraries 
library(sf)  # Load sf for handling spatial data and shapefiles
## Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE
library(tmap)  # Load tmap for creating interactive and static maps
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library(tidycensus)  # Load tidycensus for accessing U.S. Census Bureau data directly
library(dplyr)     # For data manipulation functions like mutate
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
###### Question 1
# Set your Census API key ()
## census_api_key("4645b7ba2f363dfb5a199f288801acd96006ea29",install=TRUE, overwrite = TRUE)

# Retrieve Bexar County census tracts with geometry data
bexar_tracts <- get_acs(
  geography = "tract",
  variables = "B01003_001",  # Use total population variable to access boundary data
  state = "TX",
  county = "Bexar",
  geometry = TRUE,
  year = 2021
)
## Getting data from the 2017-2021 5-year ACS
## Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
##   |                                                                              |                                                                      |   0%  |                                                                              |                                                                      |   1%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |==                                                                    |   4%  |                                                                              |===                                                                   |   4%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |====                                                                  |   6%  |                                                                              |=====                                                                 |   6%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |============                                                          |  18%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |===================                                                   |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |============================                                          |  41%  |                                                                              |==============================                                        |  43%  |                                                                              |=========================================                             |  58%  |                                                                              |===========================================                           |  62%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |================================================                      |  69%  |                                                                              |===================================================                   |  73%  |                                                                              |======================================================                |  77%  |                                                                              |=========================================================             |  81%  |                                                                              |============================================================          |  85%  |                                                                              |==============================================================        |  89%  |                                                                              |=================================================================     |  93%  |                                                                              |====================================================================  |  97%  |                                                                              |====================================================================  |  98%  |                                                                              |======================================================================| 100%
# Load the "2017 BOND PROGRAM LINE" shapefile data
bond_program_line <- st_read("C:/Users/dagob/OneDrive/Desktop/Assignment 4/BondProjectLines2017/BondProjectLines2017.shp")
## Reading layer `BondProjectLines2017' from data source 
##   `C:\Users\dagob\OneDrive\Desktop\Assignment 4\BondProjectLines2017\BondProjectLines2017.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 69 features and 24 fields
## Geometry type: MULTILINESTRING
## Dimension:     XY
## Bounding box:  xmin: 2078269 ymin: 13665110 xmax: 2168346 ymax: 13783530
## Projected CRS: NAD83 / Texas South Central (ftUS)
# Set tmap to interactive mode             
tmap_mode("view")
## tmap mode set to interactive viewing
# Create the map with census tracts as the background and bond lines in green
tm_shape(bexar_tracts) +
  tm_borders() +  # Display borders for Bexar County census tracts
  tm_shape(bond_program_line) +
  tm_lines(col = "green") +  # Display bond program lines in green
  tm_layout(title = "2017 Bond Program Line with Bexar County Census Tracts")
#### Question 2 
# Load the "LIBRARIES" shapefile data
libraries <- st_read("C:/Users/dagob/OneDrive/Desktop/Assignment 4/Libraries/Libraries.shp")
## Reading layer `Libraries' from data source 
##   `C:\Users\dagob\OneDrive\Desktop\Assignment 4\Libraries\Libraries.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 30 features and 9 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 2075828 ymin: 13669570 xmax: 2170361 ymax: 13779280
## Projected CRS: NAD83 / Texas South Central (ftUS)
# Set tmap to interactive mode
tmap_mode("view")
## tmap mode set to interactive viewing
# Create the map with census tracts as the background and libraries in red
tm_shape(bexar_tracts) +
  tm_borders() +  # Display borders for Bexar County census tracts
  tm_shape(libraries) +
  tm_dots(col = "red", size = 0.5) +  # Display library points in red
  tm_layout(title = "Libraries in Bexar County with Census Tracts Background")
#### Question 3
# Define the variables we want to retrieve
variables <- c(total_population = "B01003_001E", poverty_level = "B17017_002E")

# Retrieve ACS data for Travis County block groups in wide format
travis_data <- get_acs(
  geography = "block group",        # Set geography level to "block group"
  variables = variables,             # Specify the variables to retrieve: total population and poverty level
  state = "TX",                      # Specify the state (Texas)
  county = "Travis",                 # Specify the county (Travis County)
  geometry = TRUE,                   # Include geometry data to enable mapping
  year = 2020,                       # Specify the year of the ACS data
  output = "wide"                    # Output data in wide format for easier manipulation
)
## Getting data from the 2016-2020 5-year ACS
## Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
##   |                                                                              |                                                                      |   0%  |                                                                              |                                                                      |   1%  |                                                                              |==                                                                    |   3%  |                                                                              |====                                                                  |   5%  |                                                                              |=====                                                                 |   8%  |                                                                              |=======                                                               |  10%  |                                                                              |=========                                                             |  13%  |                                                                              |=======================                                               |  32%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |============================                                          |  40%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |================================                                      |  45%  |                                                                              |=================================                                     |  48%  |                                                                              |===================================                                   |  50%  |                                                                              |======================================                                |  54%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |===========================================                           |  61%  |                                                                              |===============================================                       |  68%  |                                                                              |=================================================                     |  70%  |                                                                              |=============================================================         |  88%  |                                                                              |======================================================================| 100%
# Calculate poverty rate by dividing poverty level by total population
travis_data <- travis_data %>%
  mutate(poverty_rate = poverty_level / total_population)


# Set tmap to interactive mode to enable a dynamic map
tmap_mode("view")
## tmap mode set to interactive viewing
# Create map showing poverty rate with a green to red color gradient
# Start creating the map by defining the base shape data
tm_shape(travis_data) +   
  tm_polygons(
    col = "poverty_rate",          # Use the poverty_rate column to define polygon colors
    palette = "RdYlGn",       # Apply RdYlGn color palette with multiple contrasting colors
    title = "Poverty Rate"         # Set the title for the legend to "Poverty Rate"
  ) +  tm_layout(
    title = "Poverty Rate in Travis County Block Groups"  # Set the main title for the map
  )
#### Question 4
# Retrieve Bexar County census tracts with geometry data
bexar_tracts <- get_acs(
  geography = "tract",
  variables = "B01003_001",  # Use total population variable to access boundary data
  state = "TX",
  county = "Bexar",
  geometry = TRUE,
  year = 2021
)
## Getting data from the 2017-2021 5-year ACS
## Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
# Check and set the coordinate systems for Bexar County census tracts and Libraries data
# Ensure that both datasets are using the same coordinate reference system (CRS)
# Check the CRS of both datasets
st_crs(bexar_tracts)    # Display CRS of bexar_tracts
## Coordinate Reference System:
##   User input: NAD83 
##   wkt:
## GEOGCRS["NAD83",
##     DATUM["North American Datum 1983",
##         ELLIPSOID["GRS 1980",6378137,298.257222101,
##             LENGTHUNIT["metre",1]]],
##     PRIMEM["Greenwich",0,
##         ANGLEUNIT["degree",0.0174532925199433]],
##     CS[ellipsoidal,2],
##         AXIS["latitude",north,
##             ORDER[1],
##             ANGLEUNIT["degree",0.0174532925199433]],
##         AXIS["longitude",east,
##             ORDER[2],
##             ANGLEUNIT["degree",0.0174532925199433]],
##     ID["EPSG",4269]]
st_crs(libraries)       # Display CRS of libraries
## Coordinate Reference System:
##   User input: NAD83 / Texas South Central (ftUS) 
##   wkt:
## PROJCRS["NAD83 / Texas South Central (ftUS)",
##     BASEGEOGCRS["NAD83",
##         DATUM["North American Datum 1983",
##             ELLIPSOID["GRS 1980",6378137,298.257222101,
##                 LENGTHUNIT["metre",1]]],
##         PRIMEM["Greenwich",0,
##             ANGLEUNIT["degree",0.0174532925199433]],
##         ID["EPSG",4269]],
##     CONVERSION["SPCS83 Texas South Central zone (US survey foot)",
##         METHOD["Lambert Conic Conformal (2SP)",
##             ID["EPSG",9802]],
##         PARAMETER["Latitude of false origin",27.8333333333333,
##             ANGLEUNIT["degree",0.0174532925199433],
##             ID["EPSG",8821]],
##         PARAMETER["Longitude of false origin",-99,
##             ANGLEUNIT["degree",0.0174532925199433],
##             ID["EPSG",8822]],
##         PARAMETER["Latitude of 1st standard parallel",30.2833333333333,
##             ANGLEUNIT["degree",0.0174532925199433],
##             ID["EPSG",8823]],
##         PARAMETER["Latitude of 2nd standard parallel",28.3833333333333,
##             ANGLEUNIT["degree",0.0174532925199433],
##             ID["EPSG",8824]],
##         PARAMETER["Easting at false origin",1968500,
##             LENGTHUNIT["US survey foot",0.304800609601219],
##             ID["EPSG",8826]],
##         PARAMETER["Northing at false origin",13123333.333,
##             LENGTHUNIT["US survey foot",0.304800609601219],
##             ID["EPSG",8827]]],
##     CS[Cartesian,2],
##         AXIS["easting (X)",east,
##             ORDER[1],
##             LENGTHUNIT["US survey foot",0.304800609601219]],
##         AXIS["northing (Y)",north,
##             ORDER[2],
##             LENGTHUNIT["US survey foot",0.304800609601219]],
##     USAGE[
##         SCOPE["Engineering survey, topographic mapping."],
##         AREA["United States (USA) - Texas - counties of Aransas; Atascosa; Austin; Bandera; Bee; Bexar; Brazoria; Brewster; Caldwell; Calhoun; Chambers; Colorado; Comal; De Witt; Dimmit; Edwards; Fayette; Fort Bend; Frio; Galveston; Goliad; Gonzales; Guadalupe; Harris; Hays; Jackson; Jefferson; Karnes; Kendall; Kerr; Kinney; La Salle; Lavaca; Live Oak; Matagorda; Maverick; McMullen; Medina; Presidio; Real; Refugio; Terrell; Uvalde; Val Verde; Victoria; Waller; Wharton; Wilson; Zavala."],
##         BBOX[27.78,-105,30.67,-93.76]],
##     ID["EPSG",2278]]
# Transform both datasets to WGS84 (EPSG: 4326) for consistency
bexar_tracts <- st_transform(bexar_tracts, crs = 4326)
libraries <- st_transform(libraries, crs = 4326)

# Perform overlay analysis to find the census tract for each library
libraries_in_tracts <- st_join(libraries, bexar_tracts, join = st_within)

# Print the result to verify each library is matched with a census tract
print(libraries_in_tracts)
## Simple feature collection with 30 features and 14 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -98.66264 ymin: 29.33487 xmax: -98.36605 ymax: 29.63648
## Geodetic CRS:  WGS 84
## First 10 features:
##                     Name                        Address        Phone Zipcode
## 1       Schaeffer Branch               6322 US Hwy 87 E         <NA>   78222
## 2  Collins Garden Branch                200 N Park Blvd 210.225.0331   78204
## 3       San Pedro Branch            1315  San Pedro Ave 210.733.1454   78212
## 4        John Igo Branch          13330 Kyle Seale Pkwy 210.561.6113   78249
## 5    Forest Hills Branch                 5245 Ingram Rd 210.431.2544   78228
## 6   Thousand Oaks Branch            4618  Thousand Oaks 210.657.5205   78233
## 7         Oakwell Branch        4134  Harry Wurzbach Rd 210.828.2569   78209
## 8          Parman Branch           20735 Wilderness Oak 210.207.2703   78258
## 9        Memorial Branch                  3222  Culebra 210.432.6783   78228
## 10       Potranco Branch 8765 State Hwy 151 (Access Rd)         <NA>   78250
##    Number PrefixDire      StreetName StreetType
## 1    6322          E       HWY US 87        HWY
## 2     200          N            PARK       BLVD
## 3    1315       <NA>       SAN PEDRO        AVE
## 4   13330       <NA> KYLE SEALE PWKY       <NA>
## 5    5245       <NA>          INGRAM         RD
## 6    4618       <NA>   THOUSAND OAKS       <NA>
## 7    4134       <NA>  HARRY WURZBACH         RD
## 8    <NA>       <NA>  WILDERNESS OAK       <NA>
## 9    3222       <NA>         CULEBRA       <NA>
## 10   8765       <NA>  StTATE HWY 151        HWY
##                                         Website       GEOID
## 1                                          <NA> 48029131401
## 2  www.sat.lib.tx.us/branches/collinsgarden.htm 48029160200
## 3       www.sat.lib.tx.us/branches/sanpedro.htm 48029190100
## 4     www.sanantonio.gov/library/branch/igo.asp 48029181824
## 5    www.sat.lib.tx.us/branches/foresthills.htm 48029180501
## 6         www.sat.lib.tx.us/branches/thoaks.htm 48029121205
## 7        www.sat.lib.tx.us/branches/oakwell.htm 48029120902
## 8                                          <NA> 48029191811
## 9       www.sat.lib.tx.us/branches/memorial.htm 48029171301
## 10                                         <NA> 48029171926
##                                         NAME   variable estimate  moe
## 1  Census Tract 1314.01, Bexar County, Texas B01003_001    11242 1340
## 2     Census Tract 1602, Bexar County, Texas B01003_001     2970  424
## 3     Census Tract 1901, Bexar County, Texas B01003_001     2922  577
## 4  Census Tract 1818.24, Bexar County, Texas B01003_001     3119  651
## 5  Census Tract 1805.01, Bexar County, Texas B01003_001     4930  654
## 6  Census Tract 1212.05, Bexar County, Texas B01003_001     4035  508
## 7  Census Tract 1209.02, Bexar County, Texas B01003_001     6586 1188
## 8  Census Tract 1918.11, Bexar County, Texas B01003_001     4059  432
## 9  Census Tract 1713.01, Bexar County, Texas B01003_001     2815  618
## 10 Census Tract 1719.26, Bexar County, Texas B01003_001     2501  323
##                      geometry
## 1  POINT (-98.36605 29.39328)
## 2  POINT (-98.51508 29.39835)
## 3  POINT (-98.50159 29.44702)
## 4  POINT (-98.64343 29.57044)
## 5  POINT (-98.58884 29.46413)
## 6   POINT (-98.4015 29.54507)
## 7  POINT (-98.43386 29.51066)
## 8  POINT (-98.51492 29.63648)
## 9  POINT (-98.56427 29.44865)
## 10 POINT (-98.66067 29.44238)