# SPDS
library(tidyverse)
library(sf)
library(units)

# Data
library(USAboundaries)
library(rnaturalearth)

# Visualization
library(gghighlight)
library(ggrepel)
library(knitr)

Question 1

#1.1
eqdc = '+proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs'

#1.2
conus = USAboundaries::us_states(resolution="low") %>%
  filter(!state_name %in% c("Puerto Rico",
                            "Alaska",
                            "Hawaii")) %>% 
  st_transform(eqdc)
st_geometry(conus)
## Geometry set for 49 features 
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -2230934 ymin: -1612761 xmax: 2124154 ymax: 1271087
## CRS:            +proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
## First 5 geometries:
#1.3
boundary_sf = st_as_sf(rnaturalearth::countries110, 
                      coords = c("X", "Y"), 
                      crs = 4326) %>% 
  filter(admin %in% c("Canada",
                            "United States of America",
                            "Mexico")) %>% 
  st_transform(eqdc)
st_geometry(boundary_sf)
## Geometry set for 3 features 
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -5994461 ymin: -2812859 xmax: 2982938 ymax: 4936902
## CRS:            +proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
plot(boundary_sf)

#1.4
cities=read_csv("../data/uscities.csv")
head(cities)
## # A tibble: 6 x 19
##   city  city_ascii state_id state_name county_fips county_name county_fips_all
##   <chr> <chr>      <chr>    <chr>            <dbl> <chr>       <chr>          
## 1 Sout~ South Cre~ WA       Washington       53053 Pierce      53053          
## 2 Rosl~ Roslyn     WA       Washington       53037 Kittitas    53037          
## 3 Spra~ Sprague    WA       Washington       53043 Lincoln     53043          
## 4 Gig ~ Gig Harbor WA       Washington       53053 Pierce      53053          
## 5 Lake~ Lake Cass~ WA       Washington       53061 Snohomish   53061          
## 6 Teni~ Tenino     WA       Washington       53067 Thurston    53067          
## # ... with 12 more variables: county_name_all <chr>, lat <dbl>, lng <dbl>,
## #   population <dbl>, density <dbl>, source <chr>, military <lgl>,
## #   incorporated <lgl>, timezone <chr>, ranking <dbl>, zips <chr>, id <dbl>
cities_sf=st_as_sf(cities,
                   coords=c("lng","lat"),
                   crs= 4326) %>% 
  filter(!state_name %in% c("Puerto Rico",
                            "Alaska",
                            "Hawaii")) %>% 
  st_cast("POINT") %>% 
  select(city, state_name, county_name, population) %>% 
  st_transform(eqdc)
st_geometry(cities_sf)
## Geometry set for 28145 features 
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: -2224952 ymin: -1601803 xmax: 2115970 ymax: 1275643
## CRS:            +proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
## First 5 geometries:

Question 2

#2.1
us_u_ml = st_union(conus) %>%
  st_cast("MULTILINESTRING") 

cities_sf=mutate(cities_sf ,distance_to_usb = 
                   set_units(st_distance(cities_sf, 
                               us_u_ml), "km"))
st_geometry(us_u_ml)
## Geometry set for 1 feature 
## geometry type:  MULTILINESTRING
## dimension:      XY
## bbox:           xmin: -2230934 ymin: -1612761 xmax: 2124154 ymax: 1271087
## CRS:            +proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
farthest_from_border = cities_sf %>% 
  slice_max(distance_to_usb, n = 5) %>% 
  select(city, state_name, distance_to_usb) %>% 
  st_drop_geometry()

knitr::kable(farthest_from_border, 
             caption = "Furthest Cities From the US Border",
             col.names = c("City", "State", "Distance"),
             format.args = list(big.mark = ","))
Furthest Cities From the US Border
City State Distance
Dresden Kansas 1,012.317 [km]
Herndon Kansas 1,007.750 [km]
Hill City Kansas 1,005.147 [km]
Atwood Kansas 1,004.734 [km]
Jennings Kansas 1,003.646 [km]
#2.2
us_c_ml = st_combine(conus) %>%
  st_cast("MULTILINESTRING") 

cities_sf=mutate(cities_sf ,distance_to_stateb = 
                   set_units(st_distance(cities_sf, 
                               us_c_ml), "km"))
st_geometry(us_c_ml)
## Geometry set for 1 feature 
## geometry type:  MULTILINESTRING
## dimension:      XY
## bbox:           xmin: -2230934 ymin: -1612761 xmax: 2124154 ymax: 1271087
## CRS:            +proj=eqdc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
farthest_from_stateborder = cities_sf %>% 
  slice_max(distance_to_stateb, n = 5) %>% 
  select(city, state_name, distance_to_stateb) %>% 
  st_drop_geometry()

knitr::kable(farthest_from_stateborder, 
             caption = "Furthest Cities From a State Border",
             col.names = c("City", "State", "Distance"),
             format.args = list(big.mark = ","))
Furthest Cities From a State Border
City State Distance
Lampasas Texas 308.9216 [km]
Bertram Texas 302.8190 [km]
Kempner Texas 302.5912 [km]
Harker Heights Texas 298.8125 [km]
Florence Texas 298.6804 [km]
#2.3
mexican_border=boundary_sf %>% 
  filter(admin %in% "Mexico") %>% 
  st_combine() %>% 
  st_cast("MULTILINESTRING")

cities_sf=mutate(cities_sf ,distance_to_mexico = 
                   set_units(st_distance(cities_sf, 
                               mexican_border), "km"))

farthest_from_mexico = cities_sf %>% 
  slice_max(distance_to_mexico, n = 5) %>% 
  select(city, state_name, distance_to_mexico) %>% 
  st_drop_geometry()

knitr::kable(farthest_from_mexico, 
             caption = "Furthest Cities From the US-Mexico Border",
             col.names = c("City", "State", "Distance"),
             format.args = list(big.mark = ","))
Furthest Cities From the US-Mexico Border
City State Distance
Caribou Maine 3,250.334 [km]
Presque Isle Maine 3,234.570 [km]
Calais Maine 3,134.348 [km]
Eastport Maine 3,125.624 [km]
Old Town Maine 3,048.366 [km]
#2.4
canadian_border=boundary_sf %>% 
  filter(admin %in% "Canada") %>% 
  st_combine() %>% 
  st_cast("MULTILINESTRING")

cities_sf=mutate(cities_sf ,distance_to_canada = 
                   set_units(st_distance(cities_sf, 
                               canadian_border), "km"))

farthest_from_canada = cities_sf %>% 
  slice_max(distance_to_canada, n = 5) %>% 
  select(city, state_name, distance_to_canada) %>% 
  st_drop_geometry()

knitr::kable(farthest_from_canada, 
             caption = "Furthest Cities From the US-Canada Border",
             col.names = c("City", "State", "Distance"),
             format.args = list(big.mark = ","))
Furthest Cities From the US-Canada Border
City State Distance
Guadalupe Guerra Texas 2,206.455 [km]
Sandoval Texas 2,205.641 [km]
Fronton Texas 2,204.784 [km]
Fronton Ranchettes Texas 2,202.118 [km]
Evergreen Texas 2,202.020 [km]

Question 3

#3.1
ggplot() + 
  geom_sf(data = canadian_border, lty = 1, size = 1, color = "red") +
  geom_sf(data = mexican_border,lty = 1, size = 1, color = "green") +
  geom_sf(data = us_u_ml,lty = 1, size = 1, color = "blue") +
  geom_sf(data = us_c_ml, lty = 3)+
  geom_sf(data = (cities_sf %>% 
                    slice_max(population, n = 10)), 
                  size = 2, color = "red") +
  ggrepel::geom_label_repel(
    data = (cities_sf %>% 
                    slice_max(population, n = 10)),
    aes(label = city, geometry = geometry),
    stat = "sf_coordinates",
    size = 2) +
  ggthemes::theme_map() 

#3.2
ggplot() + 
  geom_sf(data = us_u_ml, size = 1, fill = "NA") +
  geom_sf(data = drop_units(cities_sf), aes(color = distance_to_usb), size = .5) + 
  scale_color_gradient(low = 'darkgreen', high = "orange") +
  ggrepel::geom_label_repel(
    data = (cities_sf %>% 
                    slice_max(distance_to_usb, n = 5)),
    aes(label = city, geometry = geometry),
    stat = "sf_coordinates",
    size = 3) +
  ggthemes::theme_map() 

#3.3
ggplot() + 
  geom_sf(data = us_c_ml, 
          size = 1, 
          fill = "NA") +
  geom_sf(data = drop_units(cities_sf), 
          aes(color = distance_to_stateb), 
          size = 1) + 
  scale_color_gradient(low = 'darkgreen', 
                       high = "orange") +
  ggrepel::geom_label_repel(
    data = (cities_sf %>% 
                    slice_max(distance_to_stateb, n = 5)),
    aes(label = city, geometry = geometry),
    stat = "sf_coordinates",
    size = 3) +
  ggthemes::theme_map() 

#3.4
cities_sf= mutate(cities_sf, equidistance= abs(distance_to_mexico-distance_to_canada))

ggplot()+
  geom_sf(data = us_u_ml, size = 1, fill = "NA")+
  geom_sf(data = drop_units(cities_sf), 
          aes(color = equidistance), 
          size = .5)+
  scale_color_gradient(low = 'red', high = "blue") +
  gghighlight(equidistance < 100) +
  ggrepel::geom_label_repel(
    data = (drop_units(cities_sf) %>% 
              filter(equidistance < 100) %>% 
              slice_max(population, n = 5)),
    aes(label = city, geometry = geometry),
    stat = "sf_coordinates",
    size = 3) +
  ggthemes::theme_map() 

Question 4