library(terra)
## terra 1.7.71
library(tidyterra)
## 
## Attaching package: 'tidyterra'
## The following object is masked from 'package:stats':
## 
##     filter
library(sp)
library(ggplot2)
library(ggthemes)
library(urbnmapr)
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(leaflet)
library(dplyr)   
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:terra':
## 
##     intersect, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(spData) 
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
setwd("/Users/erlisakabashi/Desktop/dida 370/homework")
crimez <- read.csv("misdemeanor_felony1.csv", header= T)

setwd("/Users/erlisakabashi/Desktop/dida 370/homework/NE1_50M_SR_W")
rastur <- rast("NE1_50M_SR_W.tif")
rastur <- terra::project(rastur, "EPSG:4326", method = "bilinear")
## 
|---------|---------|---------|---------|
=========================================
                                          
states <- get_urbn_map("states", sf = TRUE)
states <- states %>% st_transform("EPSG:4326")
## old-style crs object detected; please recreate object with a recent sf::st_crs()
us_rast <- crop(rastur, states)
continental <- states[-c(50,51),]

ggplot()+ 
  geom_spatraster(data = us_rast)+
  geom_sf(continental, mapping = aes(), fill = 'transparent', color = "black")+
  theme_map()+
  scale_fill_whitebox_c(
    palette = "soft",
    na.value = "white")+
  labs(title = "Landcover in Continental US", fill = "Fill")+
  theme(plot.title = element_text(hjust = 0.5, size = 16),
        legend.position="right") +
  scale_fill_gradient(name = "Fill", low = "darkgreen",
                   high = "yellow")
## <SpatRaster> resampled to 500636 cells for plotting
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.
## ! `tidyterra::geom_spatraster()`: Plotting 3 overlapping layers: NE1_50M_SR_W_1, NE1_50M_SR_W_2, and NE1_50M_SR_W_3. Either:
## 
##   Use `facet_wrap(~lyr)` for faceting or
## 
##   Use `aes(fill = <name_of_layer>)` for displaying single layers

counties <- get_urbn_map("counties", sf = TRUE)
counties <- counties %>%filter(state_abbv == "NY") %>% st_transform("EPSG:32116")
## old-style crs object detected; please recreate object with a recent sf::st_crs()
library(tidyr)
## 
## Attaching package: 'tidyr'
## The following object is masked from 'package:terra':
## 
##     extract
counties1 <- counties %>% 
  separate(county_name, c("county_name", "county"), sep = " County") %>% 
  select(-county)

felonies<-crimez %>% select(County, Total.Felony, Drug2, Violent3, DWI4, Other5) 
misdemeanors<- crimez %>% select(County, Total.Misdemeanor, Drug2.1, DWI4.1, Property6, Other5.1) 

county_data_felon <- counties1 %>% left_join(felonies,by = c("county_name" = "County"))
county_data_misd <- counties1 %>% left_join(misdemeanors,by = c("county_name" = "County"))

county_data_felon = st_transform(county_data_felon, "EPSG:4326")
county_data_misd = st_transform(county_data_misd, "EPSG:4326")

county_data_felon <- county_data_felon %>% mutate(pct.drug = county_data_felon$Drug2/county_data_felon$Total.Felony)
county_data_misd <- county_data_misd %>% mutate(pct.drug1 = county_data_misd$Drug2.1/county_data_misd$Total.Misdemeanor)
p_popup <- paste0("<strong>County: </strong>", county_data_felon$county_name, " ", "<br>", 
                  "<strong>Percentage of Drug Felonies: </strong>", round(county_data_felon$pct.drug*100,2), "%")
p_popup2 <- paste0("<strong>County: </strong>", county_data_misd$county_name, " ", "<br>", 
                  "<strong>Percentage of Drug Misdemeanors: </strong>", round(county_data_misd$pct.drug1*100,2), "%")

pal_fun <- colorBin("YlOrRd", county_data_felon$pct.drug, pretty = F)
pal_fun2<-colorBin("Accent", county_data_misd$pct.drug1, pretty = F)

leaflet() %>%
  leaflet::addPolygons(data = county_data_felon, 
                       stroke = FALSE,   
                       fillColor = ~pal_fun(pct.drug), #set fill color with function from above and value
                       fillOpacity = 0.8, 
                       smoothFactor = 0.5, #add popup
                       popup = p_popup,
                       group = 'Felonies')%>%
  leaflet::addPolygons(data = county_data_misd, 
                       stroke = FALSE,    
                       fillColor = ~pal_fun2(pct.drug1), #set fill color with function from above and value
                       fillOpacity = 0.8, 
                       smoothFactor = 0.5, #add popup
                       popup = p_popup2,
                       group = 'Misdemeanors')%>%
  addLegend("bottomleft", pal = pal_fun,
            values=county_data_felon$pct.drug, 
            title = "Share of Felonies Pertaining To Drugs",
            group = 'Felonies')%>%
  addLegend("bottomleft", pal = pal_fun2,
            values=county_data_misd$pct.drug1, 
            title = "Share of Misdemeanors Pertaining To Drugs",
            group = 'Misdemeanors') %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addLayersControl(overlayGroups = c("Felonies", "Misdemeanors"),
                   options = layersControlOptions(collapsed = FALSE))