Lauren DeMarco Assignment 3

library(terra)
## Warning: package 'terra' was built under R version 4.2.3
## terra 1.7.71
library(tidyterra)
## Warning: package 'tidyterra' was built under R version 4.2.3
## 
## Attaching package: 'tidyterra'
## The following object is masked from 'package:stats':
## 
##     filter
library(sp)
## Warning: package 'sp' was built under R version 4.2.3
library(ggplot2)
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 4.2.3
library(urbnmapr)
library(sf)
## Warning: package 'sf' was built under R version 4.2.3
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
setwd("/Users/laurendemarco/Downloads/DIDA370")

rast <- rast("NE1_50M_SR_W.tif")
#rast <- terra::project(rast, "EPSG:32116", method = "bilinear")

rast
## class       : SpatRaster 
## dimensions  : 5400, 10800, 3  (nrow, ncol, nlyr)
## resolution  : 0.03333333, 0.03333333  (x, y)
## extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326) 
## source      : NE1_50M_SR_W.tif 
## colors RGB  : 1, 2, 3 
## names       : NE1_50M_SR_W_1, NE1_50M_SR_W_2, NE1_50M_SR_W_3

map 1 static

plot(rast) #on it own it is a full world map

#need to use the crop function and a US states basemap to map only the United States

#state_map.shp
states <- get_urbn_map("states", sf = TRUE)
states  %>% 
  st_transform("EPSG:32116")
## old-style crs object detected; please recreate object with a recent sf::st_crs()
plot (states)
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()
## old-style crs object detected; please recreate object with a recent sf::st_crs()

#running this before the next cell is the the only way I was able to get it to work
#storing the crs info into variable 
#Found the info for how to do this here, https://gis.stackexchange.com/questions/111226/how-to-assign-crs-to-rasterlayer-in-r
crs_rast <- crs(rast) 
crs_states <- st_crs(states)
## old-style crs object detected; please recreate object with a recent sf::st_crs()
#make states' geometry to match raster CRS if they are not the same
#i learned how to work with if statements in HARP 150 and HARP 151
if (!identical(crs_rast, crs_states)) {
  states <- st_transform(states, crs = crs_rast) #getting the info to match between state and raster data
}
## old-style crs object detected; please recreate object with a recent sf::st_crs()
US_map <- mask(rast, states) #working with the st_crop and crop functions did not work for me, so I tried the mask function which I saw here: https://datacarpentry.org/semester-biology/materials/spatial-data-cropping-R/ and it did work! 
## 
|---------|---------|---------|---------|
=========================================
                                          
plot(US_map)

#create the US map only with the state outline, same thing before just displayed differently 
ggplot()+
  geom_spatraster(data = US_map)+
  geom_sf(data = states, mapping = aes(), color = "pink")+
  theme_map()+
  scale_fill_whitebox_c(
    na.value = "white")+
  labs(title = "Map of US",
       fill = "Fill")+
  theme(plot.title = element_text(hjust = 0.5, size = 16),
        legend.position="right")
## <SpatRaster> resampled to 5e+05 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

map 2 dynamic 2 variable

library(leaflet)
## Warning: package 'leaflet' was built under R version 4.2.3
#my map of NY counties
counties <- get_urbn_map("counties", sf = TRUE)

#filter the data to get just NYS
counties <- counties %>% 
  filter(state_abbv == "NY") %>% 
  st_transform("EPSG:4326")
## old-style crs object detected; please recreate object with a recent sf::st_crs()
#base leaflet map
leaflet() %>%
  leaflet::addPolygons(data = counties,
                       color = "green")
#hogs by inventory 
hogs <- st_read("N-30.xls")
## Multiple layers are present in data source /Users/laurendemarco/Downloads/DIDA370/N-30.xls, reading layer `Hogs'.
## Use `st_layers' to list all layer names and their type in a data source.
## Set the `layer' argument in `st_read' to read a particular layer.
## Warning in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
## automatically selected the first layer in a data source containing more than
## one.
## Reading layer `Hogs' from data source 
##   `/Users/laurendemarco/Downloads/DIDA370/N-30.xls' using driver `XLS'
## Warning: no simple feature geometries present: returning a data.frame or tbl_df
hogs
#do not need all the hog data, just this
hogs_updated <- hogs %>% 
  select (Field1, Field2, Field5)

#rename columns
colnames(hogs_updated) <- c("county_name","2012","1997")

#only take specifc columns from the datasete
hogs_updated <- hogs_updated[7:63, ] #learned how to do this in DIDA 325 final project working with manipulting and cleaning data 
#in counties data could drop the word "County" and " " to create uniformity for a future merge
counties$county_name <- gsub("County", "", counties$county_name)
counties$county_name <- gsub(" ", "", counties$county_name)
hogs_updated$county_name <- gsub(" ", "", hogs_updated$county_name)
#combined dataset with the hog data and geospatial data
merged_county <- merge(counties, hogs_updated, by = "county_name", all.x = TRUE) #learned how to do merges this past summer working as an analyst intern, but also can include a link on syntax: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/merge 

#select columns from one big dataframe
updated_data <- merged_county %>% 
  select(county_name, "2012", "1997", geometry)

updated_data$`2012` <- as.numeric(updated_data$`2012`) #making sure the year columns are numeric, learned in DIDA 325
## Warning: NAs introduced by coercion
updated_data$`1997` <- as.numeric(updated_data$`1997`)
## Warning: NAs introduced by coercion
#2012 data
map1 <- leaflet() %>%
  addTiles() %>%  # Add default tile layer
  addPolygons(data = updated_data,
              fillColor = ~colorQuantile("YlOrRd", updated_data$`2012`)(`2012`),  # Fill color based on 2012 data
              fillOpacity = 0.6,  # Opacity of fill
              color = "black",
              weight = 1, # Border color
              popup = ~paste("County:", county_name, "<br>", "2012 Data:", `2012`))   %>% 
  addLegend("bottomright",  
            pal = colorQuantile("YlOrRd", updated_data$`2012`),
            values=updated_data$'2012', 
            title = '2012',
            group = "2012")

map1
#1997 data
map2 <- leaflet() %>%
  addTiles() %>%  # Add default tile layer
  addPolygons(data = updated_data,
              fillColor = ~colorQuantile("YlOrRd", updated_data$`1997`)(`1997`),  # Fill color based on 1997 data
              fillOpacity = 0.6,  # Opacity of fill
              color = "black",
              weight = 1, # Border color
              popup = ~paste("County:", county_name, "<br>", "1997 Data:", `1997`)) %>% 
  addLegend("bottomright",  
            pal = colorQuantile("YlOrRd", updated_data$`1997`),
            values=updated_data$'1997', 
            title = '1997',
            group = "1997")

map2

Combining the two maps and making it dynamic, Final map 2

leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(data = updated_data,
              fillColor = ~colorQuantile("YlOrRd", updated_data$`2012`)(`2012`),  
              fillOpacity = 0.6,
              color = "black",
              weight = 1,
              popup = ~paste("County:", updated_data$county_name, "<br>", "2012 Data:", updated_data$`2012`), 
              group = "2012") %>% 
  addPolygons(data = updated_data,
              fillColor = ~colorQuantile("YlOrRd", updated_data$`1997`)(`1997`), 
              fillOpacity = 0.6,  
              color = "black",
              weight = 1, 
              popup = ~paste("County:", updated_data$county_name, "<br>", "1997 Data:", updated_data$`1997`), 
              group = "1997") %>% 
  addLegend("bottomright",  
            pal = colorQuantile("YlOrRd", updated_data$`2012`),
            values=updated_data$'2012', 
            title = '2012',
            group = "2012") %>% 
  addLegend("bottomright",  
            pal = colorQuantile("YlOrRd", updated_data$`1997`),
            values=updated_data$'1997', 
            title = '1997',
            group = "1997") %>%  
  addLayersControl(overlayGroups = c("2012", "1997"),
                   options = layersControlOptions(collapsed = FALSE))