library(tidycensus)
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(tmap)
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, will retire in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
## The sp package is now running under evolution status 2
##      (status 2 uses the sf package in place of rgdal)
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library(tigris)
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
library(raster)
## Loading required package: sp
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
#Q1
census_api_key("0d539976d5203a96fa55bbf4421110d4b3db3648",install="TRUE", overwrite = TRUE)
## Your original .Renviron will be backed up and stored in your R HOME directory if needed.
## Your API key has been stored in your .Renviron and can be accessed by Sys.getenv("CENSUS_API_KEY"). 
## To use now, restart R or run `readRenviron("~/.Renviron")`
## [1] "0d539976d5203a96fa55bbf4421110d4b3db3648"
var=c('B19013_001E','B03002_012E','B03002_004E','B01001_002E', 'B01001_026E', 'B01003_001E', 'B01002_001E') 
Maricopa_data <- get_acs(geography = "tract", variables = var, county = "Maricopa",
                         state = "AZ",output="wide", 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%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |======================================================================| 100%
Maricopa_data$B19013_001M <- NULL
Maricopa_data$B03002_012M <- NULL
Maricopa_data$B03002_004M <- NULL
Maricopa_data$B01001_002M <- NULL
Maricopa_data$B01001_026M <- NULL
Maricopa_data$B01003_001M <- NULL
Maricopa_data$B01002_001M <- NULL
names(Maricopa_data)[3] <- 'HHIncome'
names(Maricopa_data)[4] <- 'Hispanic'
names(Maricopa_data)[5] <- 'Black'
names(Maricopa_data)[6] <- 'Male'
names(Maricopa_data)[7] <- 'Female'
names(Maricopa_data)[8] <- 'TotalPop'
names(Maricopa_data)[9] <- 'Age'
Maricopa_data$PercentHispanic <- 100*Maricopa_data$Hispanic/Maricopa_data$TotalPop
tm_shape(Maricopa_data) +tm_fill(col = "PercentHispanic")+ tm_layout(title = "Hispanic Population")

tm_shape(Maricopa_data) +
  tm_fill(col = "Hispanic",legend.hist = TRUE)+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_layout(legend.outside = TRUE,frame = FALSE)

#Q2
tm_shape(Maricopa_data) +
  tm_fill(col = "Hispanic",legend.hist = TRUE)+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_borders(alpha=.4) +
  tm_layout(legend.outside = TRUE,frame = FALSE)

#Q3
tm_shape(Maricopa_data) +
  tm_fill(col = "Hispanic", legend.hist = TRUE)+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_borders(alpha=.4) +
  tm_compass(type = "8star", 
             position = c("left", "BOTTOM"),
             show.labels = 2,
             text.size = 0.6) +
  tm_layout(legend.outside = TRUE,frame = TRUE)+
  tm_scale_bar(position = c("RIGHT", "BOTTOM"))

#Q4
tm_shape(Maricopa_data) +
  tm_fill(col = "Hispanic", palette = "Reds", legend.hist = TRUE)+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_borders(alpha=.4) +
  tm_compass(type = "8star", 
             position = c("left", "BOTTOM"),
             show.labels = 2,
             text.size = 0.6) +
  tm_layout(legend.outside = TRUE,frame = TRUE)+
  tm_scale_bar(position = c("RIGHT", "BOTTOM"))

#Q5
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(Maricopa_data) +
  tm_borders(alpha=0.4) +
  tm_fill(col = "PercentHispanic") + 
  tm_layout(title = "Hispanic Pop")
#Q6
maricopa_tracts<- tracts(state = "AZ", county = "Maricopa",cb=T)
## Retrieving data for the year 2021
#Q7
maricopa_trailheads <- st_read(dsn = "/Users/nicomolina/Desktop/methodsi/trailhead/trailhead.shp")
## Reading layer `Trailhead' from data source 
##   `/Users/nicomolina/Desktop/methodsi/Trailhead/Trailhead.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 165 features and 9 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 464055.4 ymin: 774856.5 xmax: 802442.2 ymax: 1083915
## Projected CRS: NAD83(HARN) / Arizona Central (ft)
buffer_distance <- 0.08
points_maricopa <- st_buffer(maricopa_trailheads, dist = buffer_distance)
tm_shape(maricopa_tracts) +
  tm_borders() +
  tm_shape(points_maricopa) +
  tm_borders(lwd = 2, col = "blue") +  
  tm_layout(frame = FALSE, title = "Maricopa Trailheads")
#Q8
maricopa_trails <-st_read(dsn = "/Users/nicomolina/Desktop/methodsi/Trail/Trail.shp")
## Reading layer `Trail' from data source 
##   `/Users/nicomolina/Desktop/methodsi/Trail/Trail.shp' using driver `ESRI Shapefile'
## Simple feature collection with 735 features and 12 fields
## Geometry type: MULTILINESTRING
## Dimension:     XY
## Bounding box:  xmin: 462708.2 ymin: 774747.3 xmax: 802445.6 ymax: 1083945
## Projected CRS: NAD83(HARN) / Arizona Central (ft)
buffer_distance <- 0.01
lines_maricopa <- st_buffer(maricopa_trails, dist = buffer_distance)
tm_shape(maricopa_tracts) +
  tm_borders() +
  tm_shape(lines_maricopa) +
  tm_borders(lwd = 2, col = "red") +  
  tm_layout(frame = FALSE, title = "Maricopa Trails")
#Q9
maricopa_parks <-st_read(dsn = "/Users/nicomolina/Desktop/methodsi/Park/Park.shp")
## Reading layer `Park' from data source 
##   `/Users/nicomolina/Desktop/methodsi/Park/Park.shp' using driver `ESRI Shapefile'
## Simple feature collection with 11 features and 24 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 460242.6 ymin: 770564.4 xmax: 803994.5 ymax: 1086836
## Projected CRS: NAD83(HARN) / Arizona Central (ft)
buffer_distance <- 0.03
polygons_maricopa <- st_buffer(maricopa_parks, dist = buffer_distance)
tm_shape(maricopa_tracts) +
  tm_borders() +
  tm_shape(polygons_maricopa) +
  tm_borders(lwd = 2, col = "yellow") +  
  tm_fill(col = "yellow")
  tm_layout(frame = FALSE, title = "Maricopa Parks")
## $tm_layout
## $tm_layout$title
## [1] "Maricopa Parks"
## 
## $tm_layout$frame
## [1] FALSE
## 
## $tm_layout$style
## [1] NA
## 
## 
## attr(,"class")
## [1] "tm"
#Q10
maricopa_ct <-tracts(state = "AZ", county = "Maricopa",cb=T)
## Retrieving data for the year 2021
maricopa_ct<-st_transform(maricopa_ct,crs = 4326)
points_maricopa_ct <- st_transform(points_maricopa, crs = 4326)
trailheads_maricopa_ct <- st_intersection(points_maricopa_ct, maricopa_ct)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
plot(trailheads_maricopa_ct)
## Warning: plotting the first 9 out of 22 attributes; use max.plot = 22 to plot
## all

#Q11
DEM_Maricopa <- raster('/Users/nicomolina/Desktop/methodsi/maricopadata/USGS_13_n34w113_20230320.tif')

#Q12
DEM_Maricopa <- setMinMax(DEM_Maricopa)
cellStats(DEM_Maricopa, min)
## [1] 165.096
cellStats(DEM_Maricopa, max)
## [1] 1440.814
#Q13
plot(DEM_Maricopa < 350, main = "Elevation criteria",
     col = c("#ffffff", "#0000ff"))

#Q14
plot(terrain(DEM_Maricopa, opt = "slope", unit = "degrees") < 3, 
     main = "Slope criteria",
     col = c("#ffffff", "#ff9900"))

#Q15
plot(terrain(DEM_Maricopa, opt = "aspect", unit = "degrees") > 22.5 &
       terrain(DEM_Maricopa, opt = "aspect", unit = "degrees") < 157.5, 
     main = "Aspect criteria")