library(base)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(remotes)
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)
## 
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
## 
##     select
library(leaflet)
library(nycgeo)
library(readr)

RESEARCH QUESTION: Find the distribution of schools in New York City based on Zip Code and the average SAT Math scores in each borough.

#read the csv file containing the information
nyc_education <- read_csv("/Users/elyshashahren/Downloads/scores.csv")
## Rows: 435 Columns: 22
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (13): School ID, School Name, Borough, Building Code, Street Address, C...
## dbl   (7): Zip Code, Latitude, Longitude, Student Enrollment, Average Score ...
## time  (2): Start Time, End Time
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#rename the column to ZIPCODE to ensure there is no gaps in the name 
names(nyc_education)[names(nyc_education) == "Zip Code"] <- "ZIPCODE" 

#group by ZIPCODE and count how many schools in each ZIPCODE area
EducationByZip <- nyc_education %>% group_by(ZIPCODE) %>% count()
# download shapefile from my library 
ourShape <- raster::shapefile('/Users/elyshashahren/Downloads/shapeBook/ZipCodes.shp')
# change ZIPCODE to character string to be able to join with shapefile 
EducationByZip$ZIPCODE <- as.character(EducationByZip$ZIPCODE)
ourShape@data <- left_join(ourShape@data, EducationByZip)
## Joining with `by = join_by(ZIPCODE)`
print(head(ourShape@data))
##   ZIPCODE BLDGZIP  PO_NAME POPULATION     AREA STATE COUNTY ST_FIPS CTY_FIPS
## 1   11436       0  Jamaica      18681 22699295    NY Queens      36      081
## 2   11213       0 Brooklyn      62426 29631004    NY  Kings      36      047
## 3   11212       0 Brooklyn      83866 41972104    NY  Kings      36      047
## 4   11225       0 Brooklyn      56527 23698630    NY  Kings      36      047
## 5   11218       0 Brooklyn      72280 36868799    NY  Kings      36      047
## 6   11226       0 Brooklyn     106132 39408598    NY  Kings      36      047
##                    URL SHAPE_AREA SHAPE_LEN  n
## 1 http://www.usps.com/          0         0 NA
## 2 http://www.usps.com/          0         0  4
## 3 http://www.usps.com/          0         0  2
## 4 http://www.usps.com/          0         0  6
## 5 http://www.usps.com/          0         0  1
## 6 http://www.usps.com/          0         0  5
# set a colour palette for the choropleth map
pal <- colorNumeric(palette = "Blues", domain=ourShape@data$n)

# plot the map by setting the map tiles, the central long and lat and zoom on the map and add the Polygons and other features like highlights and legend
leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  setView(lng = -74.0060, lat = 40.7128, zoom = 9) %>%
  addPolygons(data = ourShape, color = ~pal(n), fillOpacity = 0.8, weight = 1.3,  popup = paste0("Zip: ", ourShape@data$ZIPCODE, "<br>", "Schools: ", ourShape@data$n), highlightOptions = highlightOptions(weight=3, color="black", bringToFront = TRUE)) %>% addLegend("bottomright", pal = pal, values = ourShape@data$n, title = "Number of Schools", opacity = 0.8)
names(nyc_education)[names(nyc_education) == "Average Score (SAT Math)"] <- "average_SAT_math" 

library(ggplot2)
# nycgeo is a downloaded package with shapefile of new york based on borough
library(nycgeo)

# plot the map of average SAT Math scores in each New York borough using ggplot 
nyc_boundaries(geography = "borough") %>% 
  left_join(nyc_education, by = c("borough_name" = "Borough")) %>% ggplot() +
  geom_sf(aes(fill = average_SAT_math)) +
  theme_void() +
  theme(panel.grid = element_line(color = "transparent")) + labs(title = "Average SAT Math scores in New York by borough", 
       subtitle = "Brookyln & Bronx has the lowest SAT Math score and Manhattan has the highest ",  caption = "Created by Elysha Shahren \n Data from Kaggle") + scale_fill_continuous(name = "SAT Math score")
## old-style crs object detected; please recreate object with a recent sf::st_crs()

# updated version of map includes titles, subtitles and change to legend labels