#title: "project2"
#author: "Sophia R Wilson"
#date: "2023-11-25"
#output: html_document



#Project 02 - SRW 

#Q1
library(tidycensus)
library(ggplot2)
library(raster)
## Loading required package: sp
## 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)
library(tigris)
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
Hidalgodata <- c ("B19013_001E","B03002_012E","B01001B_001E","B01001_002E","B01001_026E","B01001_001E","B01002_001E")
Hidalgodatanew <- get_acs (geography = "tract", variables = Hidalgodata ,
                           state = "TX",county = "Hidalgo",
                           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%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |==============================                                        |  44%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
Hidalgodatanew$B19013_001M <- NULL
Hidalgodatanew$B03002_012M <- NULL
Hidalgodatanew$B01001B_001M <- NULL
Hidalgodatanew$B01001_002M <- NULL
Hidalgodatanew$B01002_001M <- NULL
Hidalgodatanew$B01001_001M <- NULL
Hidalgodatanew$B01001_026M <- NULL

names(Hidalgodatanew)[3] <- 'Median income'
names(Hidalgodatanew)[4] <- 'Hispanic population'
names(Hidalgodatanew)[5] <- 'Black population'
names(Hidalgodatanew)[6] <- 'Hidalgo male Pop.'
names(Hidalgodatanew)[7] <- 'Hidalgo female Pop.'
names(Hidalgodatanew)[8] <- 'Hidalgo Total Pop.'
names(Hidalgodatanew)[9] <- 'median age'


Hidalgodatanew <- na.omit(Hidalgodatanew)
Hidalgodatanew$Percent <- 100*Hidalgodatanew$`Black population`/Hidalgodatanew$`Hidalgo Total Pop.`
ggplot(data = Hidalgodatanew, aes(x = "Median income", y ="Percent" )) + 
  geom_point()

a <- ggplot(Hidalgodatanew, aes(x = Hidalgodatanew$`median age`))
a + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

a <- ggplot(Hidalgodatanew, aes( x=Hidalgodatanew$`Median income` ))
a + geom_density()

a <- ggplot(Hidalgodatanew, aes( x=Hidalgodatanew$`Median income` ))
a + stat_ecdf()

a <- ggplot(Hidalgodatanew, aes( x=Hidalgodatanew$`Median income` ))
a + geom_boxplot()

library(tmap)
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
tm_shape(Hidalgodatanew) +tm_fill(col = "Hispanic population")+ tm_layout(title = "Hispanic Pop map")

Hidalgodatanew$variation <- Hidalgodatanew$`Hidalgo male Pop.` - Hidalgodatanew$`Hidalgo female Pop.`
tm_shape(Hidalgodatanew) +tm_fill(col = "variation")+ tm_layout(title = "Gender Difference")
## Variable(s) "variation" contains positive and negative values, so midpoint is set to 0. Set midpoint = NA to show the full spectrum of the color palette.

x <- c(2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023)
y <- c(774769, 757433, 774820, 790646, 806447, 819217, 828344, 839539, 849389,865688, 881987, 898286, 914585, 930855)

poly.lm1 <- lm(y ~ poly(x, 1))
new.x <- c(2023, 2024, 2025, 2026, 2027, 2028)
new.df <- data.frame(x=new.x)


new.y1 <- predict(poly.lm1, newdata=new.df)
print(new.y1)
##        1        2        3        4        5        6 
## 922375.9 935356.7 948337.6 961318.4 974299.3 987280.1
#Q2 
tm_shape(Hidalgodatanew) +
  tm_borders()

#Q3
tm_shape(Hidalgodatanew) +
  tm_fill(col = "Hispanic population")+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_compass(type = "8star", 
             position = c("RIGHT", "BOTTOM"),
             show.labels = 2,
             text.size = 0.6) +
  tm_layout(legend.outside = TRUE,frame = FALSE)

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

#Q5 
library(tmap)

tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(Hidalgodatanew) +
  tm_fill(col = "Hispanic population",palette = "Reds", legend.hist = TRUE)+ 
  tm_layout(title = "Hispanic Pop")+ 
  tm_borders(alpha=.4) +
  tm_compass(type = "8star", 
             position = c("RIGHT", "BOTTOM"),
             show.labels = 2,
             text.size = 0.6) +
  tm_layout(legend.outside = TRUE,frame = FALSE)
## Compass not supported in view mode.
#Q6 
hidalgo_tracts<- tracts(state = "TX", county = "Hidalgo",cb=T)
## Retrieving data for the year 2021
#Q7 
Hidalgopoint<- st_read(dsn = "/Users/sophiawilson/Desktop/Fall 2023/Methods 1/HCADShapefiles/School__Districts.shp")
## Reading layer `School__Districts' from data source 
##   `/Users/sophiawilson/Desktop/Fall 2023/Methods 1/HCADShapefiles/School__Districts.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 16 features and 4 fields
## Geometry type: POLYGON
## Dimension:     XYZ
## Bounding box:  xmin: 955697.4 ymin: 16538850 xmax: 1193804 ymax: 16809990
## z_range:       zmin: -2.273737e-13 zmax: 4.999997e-07
## Projected CRS: NAD83 / Texas South (ftUS)
texas_counties<-counties(state = "Texas",cb=T)
## Retrieving data for the year 2021
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |                                                                      |   1%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |=======================                                               |  34%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |=====================================                                 |  54%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |======================================================================| 100%
Hidalgo<-texas_counties[texas_counties$NAME=="Hidalgo",]
Hidalgo<-st_transform(Hidalgo,crs = 4326) #define the coordinate reference system

tx_landmarks <- landmarks(state = "TX",type = 'point')
## Retrieving data for the year 2021
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |======================================================================| 100%
tx_landmarks<-st_transform(tx_landmarks,crs = 4326) #define the coordinate reference system
texas_counties <- counties(state = "TX",cb=T)
## Retrieving data for the year 2021
texas_counties<-st_transform(texas_counties,crs = 4326)

clipped_landmark_hidalgo <- st_intersection(tx_landmarks, Hidalgo)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
tm_shape(hidalgo_tracts) +
  tm_borders() +  # Add borders for polygons (customize as needed)
  tm_shape(Hidalgopoint) +
  tm_dots(size = 0.02, col = "red", alpha = 0.7) +  # Customize point appearance
  tm_basemap() +
  tm_layout(title = "School Districts", frame = FALSE)
#Q8
Road<-st_read(dsn = "/Users/sophiawilson/Desktop/Fall 2023/Methods 1/tl_2022_48215_roads/tl_2022_48215_roads.shp")
## Reading layer `tl_2022_48215_roads' from data source 
##   `/Users/sophiawilson/Desktop/Fall 2023/Methods 1/tl_2022_48215_roads/tl_2022_48215_roads.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 20990 features and 4 fields
## Geometry type: LINESTRING
## Dimension:     XY
## Bounding box:  xmin: -98.5853 ymin: 26.03714 xmax: -97.86168 ymax: 26.78298
## Geodetic CRS:  NAD83
Road<-Road[1:100,]

hidalgo_tracts<- tracts(state = "TX", county = "Hidalgo",cb=T)
## Retrieving data for the year 2021
buffer_distance <- 0.01
Road <- st_buffer(Road, dist = buffer_distance)

tm_shape(hidalgo_tracts) +
  tm_borders() +
  tm_shape(Road) +
  tm_borders(lwd = 2, col = "red") +  # Customize line appearance
  tm_layout(frame = FALSE)
#Q9
Topography <- st_read(dsn = "/Users/sophiawilson/Desktop/Fall 2023/Methods 1/tl_2022_48215_faces/tl_2022_48215_faces.shp")
## Reading layer `tl_2022_48215_faces' from data source 
##   `/Users/sophiawilson/Desktop/Fall 2023/Methods 1/tl_2022_48215_faces/tl_2022_48215_faces.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 21204 features and 45 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -98.58672 ymin: 26.03634 xmax: -97.86168 ymax: 26.78308
## Geodetic CRS:  NAD83
Topography<-Topography[1:100,]

tm_shape(Topography) +tm_fill(col = "blue")+ tm_layout(title = "Hidalgo Topography")
#Q10

hidalgo_ct <-tracts(state = "TX", county = "Hidalgo",cb=T)
## Retrieving data for the year 2021
hidalgo_ct<-st_transform(hidalgo_ct,crs = 4326)

clipped_landmark<- st_intersection(clipped_landmark_hidalgo, hidalgo_ct)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
tm_shape(hidalgo_tracts) +
  tm_borders() +  # Add borders for polygons (customize as needed)
  tm_shape(clipped_landmark) +
  tm_dots(size = 0.02, col = "red", alpha = 0.7) +  # Customize point appearance
  tm_basemap() +
  tm_layout(title = "Hidalgo Census", frame = FALSE)
plot(clipped_landmark)
## Warning: plotting the first 9 out of 30 attributes; use max.plot = 30 to plot
## all

#Q11
raster_obj <- raster("/Users/sophiawilson/Downloads/USGS_13_n27w099_20211103.tif")
plot(raster_obj)

#Q12 
DEM_SA <- raster('/Users/sophiawilson/Downloads/USGS_13_n27w099_20211103.tif')
DEM_SA <- setMinMax(DEM_SA)
cellStats(DEM_SA, max)
## [1] 239.1236
cellStats(DEM_SA, min)
## [1] 6.702944
#Q13 
plot(DEM_SA < 350, main = "Elevation criteria",
     col = c("#ffffff", "#0000ff"))

#Q14

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

#Q15

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