library(terra)
## Warning: package 'terra' was built under R version 4.3.3
## terra 1.7.71
library(tidyterra)
## Warning: package 'tidyterra' was built under R version 4.3.3
## 
## Attaching package: 'tidyterra'
## The following object is masked from 'package:stats':
## 
##     filter
library(sp)
## Warning: package 'sp' was built under R version 4.3.2
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.3
library(ggthemes)
library(urbnmapr)
library(sf)
## Warning: package 'sf' was built under R version 4.3.2
## Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
setwd("C:/Users/amode/OneDrive/Documents/DIDA370/NE1_50M_SR_W")


ny_rast <- rast("NE1_50M_SR_W.tif")

ny_rast <- terra::project(ny_rast, "EPSG:32116", method = "bilinear")
## 
|---------|---------|---------|---------|
=========================================
                                          
ny_rast
## class       : SpatRaster 
## dimensions  : 32498, 20166, 3  (nrow, ncol, nlyr)
## resolution  : 1656.569, 1656.569  (x, y)
## extent      : -16453285, 16953079, -31346642, 22488528  (xmin, xmax, ymin, ymax)
## coord. ref. : NAD83 / New York Central (EPSG:32116) 
## source      : spat_609c197fad7_24732.tif 
## names       : NE1_50M_SR_W_1, NE1_50M_SR_W_2, NE1_50M_SR_W_3 
## min values  :       69.25082,       98.07327,       104.6939 
## max values  :      255.00000,      255.00000,       255.0000
plot(ny_rast)

states <- get_urbn_map("states", sf = TRUE)
states <- states %>% 
  st_transform("EPSG:32116")
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## Warning in CPL_crs_from_input(x): GDAL Message 1: CRS EPSG:2163 is deprecated.
## Its non-deprecated replacement EPSG:9311 will be used instead. To use the
## original CRS, set the OSR_USE_NON_DEPRECATED configuration option to NO.
us_extent <- st_bbox(states)
#https://jsta.github.io/glatos-spatial_workshop_materials/05-vector-raster-integration/index.html
rast_us <- crop(ny_rast, states)

ggplot()+
  geom_spatraster(data = rast_us)+
  geom_sf(states, mapping = aes(), fill = 'transparent', color = "gray")+
  theme_map()+
  scale_fill_whitebox_c(
    palette = "soft",
    na.value = "white")+
  labs(title = "Landcover in US",
       fill = "Shaded relief")+
  theme(plot.title = element_text(hjust = 0.5, size = 16),
        legend.position="right")
## <SpatRaster> resampled to 500864 cells for plotting
## ! `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