# Set repository for package installations
options(repos = c(CRAN = "https://cloud.r-project.org"))

# Load required libraries
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(tmap)
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library(tidycensus)
library(tigris)  # Required for using tracts() function
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
# Download census tracts for Bexar County, Texas, using tigris
# Note: cb = TRUE to get cartographic boundaries for better visualization
bexar_ct <- tracts(state = "TX", county = "Bexar", cb = TRUE)
## Retrieving data for the year 2022
##   |                                                                              |                                                                      |   0%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |===                                                                   |   4%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |====                                                                  |   6%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |=========                                                             |  14%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |============                                                          |  18%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |===================                                                   |  28%  |                                                                              |====================                                                  |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |=====================                                                 |  31%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |=======================                                               |  34%  |                                                                              |========================                                              |  34%  |                                                                              |========================                                              |  35%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  46%  |                                                                              |=================================                                     |  47%  |                                                                              |=================================                                     |  48%  |                                                                              |==================================                                    |  48%  |                                                                              |==================================                                    |  49%  |                                                                              |===================================                                   |  49%  |                                                                              |===================================                                   |  50%  |                                                                              |====================================                                  |  51%  |                                                                              |====================================                                  |  52%  |                                                                              |=====================================                                 |  52%  |                                                                              |=====================================                                 |  53%  |                                                                              |======================================                                |  54%  |                                                                              |======================================                                |  55%  |                                                                              |=======================================                               |  55%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |========================================                              |  58%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |==========================================                            |  61%  |                                                                              |===========================================                           |  61%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  62%  |                                                                              |============================================                          |  63%  |                                                                              |=============================================                         |  64%  |                                                                              |=============================================                         |  65%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |===============================================                       |  68%  |                                                                              |================================================                      |  68%  |                                                                              |================================================                      |  69%  |                                                                              |=================================================                     |  69%  |                                                                              |=================================================                     |  70%  |                                                                              |=================================================                     |  71%  |                                                                              |==================================================                    |  71%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |===================================================                   |  74%  |                                                                              |====================================================                  |  74%  |                                                                              |====================================================                  |  75%  |                                                                              |=====================================================                 |  75%  |                                                                              |=====================================================                 |  76%  |                                                                              |======================================================                |  77%  |                                                                              |======================================================                |  78%  |                                                                              |=======================================================               |  78%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  79%  |                                                                              |========================================================              |  80%  |                                                                              |=========================================================             |  81%  |                                                                              |=========================================================             |  82%  |                                                                              |==========================================================            |  82%  |                                                                              |==========================================================            |  83%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |=============================================================         |  88%  |                                                                              |==============================================================        |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |===============================================================       |  90%  |                                                                              |===============================================================       |  91%  |                                                                              |================================================================      |  91%  |                                                                              |================================================================      |  92%  |                                                                              |=================================================================     |  93%  |                                                                              |==================================================================    |  94%  |                                                                              |==================================================================    |  95%  |                                                                              |===================================================================   |  95%  |                                                                              |===================================================================   |  96%  |                                                                              |====================================================================  |  97%  |                                                                              |====================================================================  |  98%  |                                                                              |===================================================================== |  98%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================|  99%  |                                                                              |======================================================================| 100%
# Read Bond Project Lines shapefile
bond_program_line <- st_read("/Users/jayjay/Desktop/BondProjectLines20172/BondProjectLines2017.shp")
## Reading layer `BondProjectLines2017' from data source 
##   `/Users/jayjay/Desktop/BondProjectLines20172/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)
# Plot Bexar County tracts and Bond Project Lines
tmap_mode("plot")  # Switch to plot mode
## tmap mode set to plotting
tm_shape(bexar_ct) +
  tm_borders() +
  tm_shape(bond_program_line) +
  tm_lines(col = "orange")

## Q2: Plot Libraries
# Read Libraries shapefile
libraries <- st_read("/Users/jayjay/Downloads/Libraries/Libraries.shp")
## Reading layer `Libraries' from data source 
##   `/Users/jayjay/Downloads/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)
# Plot Bexar County tracts and Libraries as points
tm_shape(bexar_ct) +
  tm_borders() +
  tm_shape(libraries) +
  tm_dots(col = "violet")

## Q3: Retrieve ACS Data and Calculate Poverty Rate
# Define variables for total population and poverty counts
var <- c(poptotal2 = 'B17017_001E', poverty = 'B17017_002E') 

# Specify state and county
st <- "TX"
ct <- "Travis"

# Retrieve block group-level ACS data for Travis County, Texas
cbg <- get_acs(geography = "block group", variables = var, county = ct,
               state = st, output = "wide", year = 2021, geometry = TRUE)
## 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%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |=========                                                             |  14%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |============                                                          |  18%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |==============                                                        |  21%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |================                                                      |  24%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |===================                                                   |  28%  |                                                                              |====================                                                  |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |=======================                                               |  34%  |                                                                              |========================                                              |  34%  |                                                                              |========================                                              |  35%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  45%  |                                                                              |================================                                      |  46%  |                                                                              |=================================                                     |  46%  |                                                                              |=================================                                     |  47%  |                                                                              |=================================                                     |  48%  |                                                                              |==================================                                    |  48%  |                                                                              |==================================                                    |  49%  |                                                                              |===================================                                   |  49%  |                                                                              |===================================                                   |  50%  |                                                                              |===================================                                   |  51%  |                                                                              |====================================                                  |  51%  |                                                                              |====================================                                  |  52%  |                                                                              |=====================================                                 |  52%  |                                                                              |=====================================                                 |  53%  |                                                                              |======================================                                |  54%  |                                                                              |======================================                                |  55%  |                                                                              |=======================================                               |  55%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |========================================                              |  58%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |==========================================                            |  61%  |                                                                              |===========================================                           |  61%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  62%  |                                                                              |============================================                          |  63%  |                                                                              |============================================                          |  64%  |                                                                              |=============================================                         |  64%  |                                                                              |=============================================                         |  65%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |===============================================                       |  68%  |                                                                              |================================================                      |  68%  |                                                                              |================================================                      |  69%  |                                                                              |=================================================                     |  69%  |                                                                              |=================================================                     |  70%  |                                                                              |==================================================                    |  71%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |===================================================                   |  74%  |                                                                              |====================================================                  |  74%  |                                                                              |====================================================                  |  75%  |                                                                              |=====================================================                 |  75%  |                                                                              |=====================================================                 |  76%  |                                                                              |======================================================                |  77%  |                                                                              |=======================================================               |  78%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  79%  |                                                                              |========================================================              |  80%  |                                                                              |========================================================              |  81%  |                                                                              |=========================================================             |  81%  |                                                                              |=========================================================             |  82%  |                                                                              |==========================================================            |  82%  |                                                                              |==========================================================            |  83%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |=============================================================         |  88%  |                                                                              |==============================================================        |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |===============================================================       |  89%  |                                                                              |===============================================================       |  90%  |                                                                              |===============================================================       |  91%  |                                                                              |================================================================      |  91%  |                                                                              |================================================================      |  92%  |                                                                              |=================================================================     |  92%  |                                                                              |=================================================================     |  93%  |                                                                              |==================================================================    |  94%  |                                                                              |==================================================================    |  95%  |                                                                              |===================================================================   |  95%  |                                                                              |===================================================================   |  96%  |                                                                              |====================================================================  |  96%  |                                                                              |====================================================================  |  97%  |                                                                              |====================================================================  |  98%  |                                                                              |===================================================================== |  98%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================|  99%  |                                                                              |======================================================================| 100%
# Calculate poverty rate
cbg$poverty_rate <- cbg$poverty / cbg$poptotal2

# Plot poverty rate in Travis County
tm_shape(cbg) +
  tm_polygons(col = "poverty_rate", palette = "RdYlGn")

## Q4: Spatial Transformation and Intersection
# Ensure both spatial objects are in the same coordinate reference system (CRS)
bexar_ct <- st_transform(bexar_ct, crs = 4326)
libraries <- st_transform(libraries, crs = 4326)

# Perform spatial intersection to find libraries within Bexar County tracts
library_ct <- st_intersection(libraries, bexar_ct)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
# Display intersection result
print(library_ct)
## Simple feature collection with 30 features and 22 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
## 10           Potranco Branch 8765 State Hwy 151 (Access Rd)         <NA>
## 25  Maury Maverick Jr Branch               8700 Mystic Park 210.680.9346
## 11 Henry A. Guerra Jr Branch            7978 W. Military Dr 210.673.1492
## 18              Bazan Branch             2200 W Commerce St 210.225.1614
## 2      Collins Garden Branch                200 N Park Blvd 210.225.0331
## 30          Roosevelt Branch                 5110 Walzem Rd 210.650.1122
## 27         Las Palmas Branch            515  Castroville Rd 210.434.6394
## 20           Kampmann Portal                210 W Market St 210.207.2500
## 22           Central Library                    600 Soledad 210.207.2500
## 8              Parman Branch           20735 Wilderness Oak 210.207.2703
##    Zipcode Number PrefixDire     StreetName StreetType
## 10   78250   8765       <NA> StTATE HWY 151        HWY
## 25   78254   8700       <NA>    MYSTIC PARK       <NA>
## 11   78227   7978          W       MILITARY         DR
## 18   78207   2200          W       COMMERCE         ST
## 2    78204    200          N           PARK       BLVD
## 30   78218   5110       <NA>         WALZEM         RD
## 27   78237    515       <NA>    CASTROVILLE         RD
## 20   78205    210          W      MARKET ST         ST
## 22   78205    600       <NA>        SOLEDAD       <NA>
## 8    78258   <NA>       <NA> WILDERNESS OAK       <NA>
##                                           Website STATEFP COUNTYFP TRACTCE
## 10                                           <NA>      48      029  171926
## 25 www.sanantonio.gov/library/branch/maverick.asp      48      029  181703
## 11   www.sanantonio.gov/library/branch/guerra.asp      48      029  171700
## 18           www.sat.lib.tx.us/branches/bazan.htm      48      029  170200
## 2    www.sat.lib.tx.us/branches/collinsgarden.htm      48      029  160200
## 30                                           <NA>      48      029  121403
## 27       www.sat.lib.tx.us/branches/laspalmas.htm      48      029  170900
## 20                                           <NA>      48      029  110100
## 22       www.sat.lib.tx.us/html/centralphotos.htm      48      029  110100
## 8                                            <NA>      48      029  191811
##                AFFGEOID       GEOID    NAME             NAMELSAD STUSPS
## 10 1400000US48029171926 48029171926 1719.26 Census Tract 1719.26     TX
## 25 1400000US48029181703 48029181703 1817.03 Census Tract 1817.03     TX
## 11 1400000US48029171700 48029171700    1717    Census Tract 1717     TX
## 18 1400000US48029170200 48029170200    1702    Census Tract 1702     TX
## 2  1400000US48029160200 48029160200    1602    Census Tract 1602     TX
## 30 1400000US48029121403 48029121403 1214.03 Census Tract 1214.03     TX
## 27 1400000US48029170900 48029170900    1709    Census Tract 1709     TX
## 20 1400000US48029110100 48029110100    1101    Census Tract 1101     TX
## 22 1400000US48029110100 48029110100    1101    Census Tract 1101     TX
## 8  1400000US48029191811 48029191811 1918.11 Census Tract 1918.11     TX
##      NAMELSADCO STATE_NAME LSAD    ALAND AWATER                   geometry
## 10 Bexar County      Texas   CT  3301430   1475 POINT (-98.66067 29.44238)
## 25 Bexar County      Texas   CT  3764552   2533 POINT (-98.64214 29.52431)
## 11 Bexar County      Texas   CT 10635977  31619 POINT (-98.62553 29.42446)
## 18 Bexar County      Texas   CT  1730790      0 POINT (-98.51954 29.42716)
## 2  Bexar County      Texas   CT  1088272      0 POINT (-98.51508 29.39835)
## 30 Bexar County      Texas   CT  4504203   8119  POINT (-98.38969 29.5094)
## 27 Bexar County      Texas   CT  1844410  13947 POINT (-98.54955 29.41818)
## 20 Bexar County      Texas   CT  3428908  13720 POINT (-98.48894 29.42293)
## 22 Bexar County      Texas   CT  3428908  13720 POINT (-98.49251 29.43203)
## 8  Bexar County      Texas   CT  6092837   2297 POINT (-98.51492 29.63648)