Lab 5

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.6
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.2     ✔ tibble    3.3.0
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(leaflet)
library(sf)
## Linking to GEOS 3.13.1, GDAL 3.11.4, PROJ 9.7.0; sf_use_s2() is TRUE
#install.packages("rgbif")
library(rgbif)
library(terra)
## terra 1.8.93
## 
## Attaching package: 'terra'
## 
## The following object is masked from 'package:tidyr':
## 
##     extract
  1. Connect with data housed in gbif (https://www.gbif.org/) to examine migration patterns of a specific species of bird (4 pts).  This selection might require some research! This is citizen science data, so you may want to select a species that is known to migrate, easy for humans to identify, and with enough observations in the database.  A great resource for looking at GBIF data - [[https://poldham.github.io/abs/gbif.html\\](https://poldham.github.io/abs/gbif.html\){.uri}

    TurkeyVulture_gbi <- readr::read_delim("N_TurkeyVulture.csv", delim = "\t", escape_double = FALSE, 
    col_names = TRUE, na = c("", "NA"))
    ## Warning: One or more parsing issues, call `problems()` on your data frame for details,
    ## e.g.:
    ##   dat <- vroom(...)
    ##   problems(dat)
    ## Rows: 1727 Columns: 50
    ## ── Column specification ────────────────────────────────────────────────────────
    ## Delimiter: "\t"
    ## chr  (32): datasetKey, occurrenceID, kingdom, phylum, class, order, family, ...
    ## dbl  (13): gbifID, individualCount, decimalLatitude, decimalLongitude, coord...
    ## lgl   (3): depth, depthAccuracy, typeStatus
    ## dttm  (2): dateIdentified, lastInterpreted
    ## 
    ## ℹ 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.
     head(TurkeyVulture_gbi)
    ## # A tibble: 6 × 50
    ##   gbifID datasetKey occurrenceID kingdom phylum class order family genus species
    ##    <dbl> <chr>      <chr>        <chr>   <chr>  <chr> <chr> <chr>  <chr> <chr>  
    ## 1 9.19e8 22a66350-… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## 2 9.19e8 22a66350-… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## 3 9.19e8 22a66350-… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## 4 8.64e8 4bfac3ea-… MCZ:Orn:354… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## 5 8.64e8 4bfac3ea-… MCZ:Orn:354… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## 6 8.64e8 4bfac3ea-… MCZ:Orn:333… Animal… Chord… Aves  Acci… Catha… Cath… Cathar…
    ## # ℹ 40 more variables: infraspecificEpithet <chr>, taxonRank <chr>,
    ## #   scientificName <chr>, verbatimScientificName <chr>,
    ## #   verbatimScientificNameAuthorship <chr>, countryCode <chr>, locality <chr>,
    ## #   stateProvince <chr>, occurrenceStatus <chr>, individualCount <dbl>,
    ## #   publishingOrgKey <chr>, decimalLatitude <dbl>, decimalLongitude <dbl>,
    ## #   coordinateUncertaintyInMeters <dbl>, coordinatePrecision <dbl>,
    ## #   elevation <dbl>, elevationAccuracy <dbl>, depth <lgl>, …
  2. Display this information (bird observations and migration) on a map via leaflet - include layers for temperature and elevation (10 pts). Add additional information that you think might be for this question. You can find inspiration in the same location here: https://poldham.github.io/abs/mapgbif.html (as well as many other sources online)

       TV_occurrence <- dplyr::rename(TurkeyVulture_gbi, latitude = decimalLatitude, 
    longitude = decimalLongitude)
    TV_occurrence%>%
      group_by(countryCode)
    ## # A tibble: 1,727 × 50
    ## # Groups:   countryCode [21]
    ##       gbifID datasetKey     occurrenceID kingdom phylum class order family genus
    ##        <dbl> <chr>          <chr>        <chr>   <chr>  <chr> <chr> <chr>  <chr>
    ##  1 919415692 22a66350-7947… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  2 919406224 22a66350-7947… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  3 919404310 22a66350-7947… urn:catalog… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  4 863555909 4bfac3ea-8763… MCZ:Orn:354… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  5 863555908 4bfac3ea-8763… MCZ:Orn:354… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  6 863509449 4bfac3ea-8763… MCZ:Orn:333… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  7 863509427 4bfac3ea-8763… MCZ:Orn:333… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  8 863389017 4bfac3ea-8763… MCZ:Orn:102… Animal… Chord… Aves  Acci… Catha… Cath…
    ##  9 863389008 4bfac3ea-8763… MCZ:Orn:429… Animal… Chord… Aves  Acci… Catha… Cath…
    ## 10 863388984 4bfac3ea-8763… MCZ:Orn:429… Animal… Chord… Aves  Acci… Catha… Cath…
    ## # ℹ 1,717 more rows
    ## # ℹ 41 more variables: species <chr>, infraspecificEpithet <chr>,
    ## #   taxonRank <chr>, scientificName <chr>, verbatimScientificName <chr>,
    ## #   verbatimScientificNameAuthorship <chr>, countryCode <chr>, locality <chr>,
    ## #   stateProvince <chr>, occurrenceStatus <chr>, individualCount <dbl>,
    ## #   publishingOrgKey <chr>, latitude <dbl>, longitude <dbl>,
    ## #   coordinateUncertaintyInMeters <dbl>, coordinatePrecision <dbl>, …
       TV_obv_summer <- TV_occurrence %>% filter(countryCode=="US" | countryCode== "CA")
    TV_obv_winter <- TV_occurrence %>% filter(countryCode !="US")%>%
      filter(countryCode != "CA")
    
    nc_data <- rast("subset.nc")
    print(crs(nc_data))
    ## [1] "GEOGCRS[\"WGS 84 (CRS84)\",\n    DATUM[\"World Geodetic System 1984\",\n        ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n            LENGTHUNIT[\"metre\",1]]],\n    PRIMEM[\"Greenwich\",0,\n        ANGLEUNIT[\"degree\",0.0174532925199433]],\n    CS[ellipsoidal,2],\n        AXIS[\"geodetic longitude (Lon)\",east,\n            ORDER[1],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        AXIS[\"geodetic latitude (Lat)\",north,\n            ORDER[2],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n    USAGE[\n        SCOPE[\"unknown\"],\n        AREA[\"World\"],\n        BBOX[-90,-180,90,180]],\n    ID[\"OGC\",\"CRS84\"]]"
    writeRaster(nc_data, filename = "temp.tif", overwrite = TRUE)
    
    temperature_raster <- rast("temp.tif")
    downsampled_temp <- aggregate(temperature_raster, fact = 4)
    
    
    leaflet() %>%
      addTiles() %>% 
      addProviderTiles(providers$Esri.NatGeoWorldMap)%>%
       addProviderTiles(providers$OpenTopoMap) %>%
    
      addRasterImage(downsampled_temp, opacity = .7,color="cyan", group = "Temperature") %>%
    
      addCircleMarkers(data=TV_obv_winter,~longitude, ~latitude, radius=.5,fillOpacity = 0.5, color = "grey",popup = ~paste("Turkey Vulture: Winter", "<br>", eventDate),
                   group = "Turkey Vulture Winter Observation")%>%
    
      addCircleMarkers(data=TV_obv_summer,~longitude, ~latitude, radius=.5,fillOpacity = 0.5, color = "purple", popup = ~paste("Turkey Vulture", "<br>", eventDate),
                   group = "Turkey Vulture: Observation")%>%
      addLayersControl(overlayGroups = c("Turkey Vulture Winter Observation", "Turkey Vulture: Observation", "Temperature"),
    options = layersControlOptions(collapsed = FALSE)
      ) %>%
      addLegend(position = "bottomright", 
            colors = c("grey", "purple","cyan"), 
            labels = c("Turkey Vulture: Winter", "Turkey Vulture","Temperature"), 
            opacity = 1)%>%
      addLegend("bottomleft", title = "Elevation",
            pal = colorNumeric(palette = c("lightgreen", "green", "darkgreen", "yellow", "orange", "red"), domain = c(0, 2000)),
            values = c(0, 2000),
            labels = c("0-200m", "201-400m", "401-600m", "601-800m", "801-1000m", "1001-2000m"),opacity = 1) 
    ## Warning in validateCoords(lng, lat, funcName): Data contains 65 rows with
    ## either missing or invalid lat/lon values and will be ignored
    ## Warning in validateCoords(lng, lat, funcName): Data contains 29 rows with
    ## either missing or invalid lat/lon values and will be ignored
  3. Label the three most populous cities near the largest set of observations for your target species (4 pts)

    TV_occurrence%>%
      group_by(locality)%>%
    count(locality)%>%
      arrange(desc(n))
    ## # A tibble: 490 × 2
    ## # Groups:   locality [490]
    ##    locality                          n
    ##    <chr>                         <int>
    ##  1 <NA>                            829
    ##  2 Brownsville                      16
    ##  3 Coronado National Forest (AZ)    14
    ##  4 Whittier                         14
    ##  5 MANGLAR EL CONCHALITO            12
    ##  6 San Juan                         12
    ##  7 CHAMETLA 1                       11
    ##  8 ENSENADA DE LA PAZ - AREA 11     11
    ##  9 Sorrento                         11
    ## 10 Alpine Valley                    10
    ## # ℹ 480 more rows
       Tucson <- data.frame(lat = 32.2540, lng = -110.9742, name = "Tucson, AZ") 
       LA <- data.frame(lat = 34.0549, lng = -118.2426, name = "Los Angeles, CA")
       Brown <- data.frame(lat = 25.9017, lng = -97.4975, name = "Brownsville, TX")
    
    map<-   leaflet() %>%
      addTiles() %>% 
      addProviderTiles(providers$Esri.NatGeoWorldMap)%>%
       addProviderTiles(providers$OpenTopoMap) %>%
    
      addRasterImage(downsampled_temp, opacity = .7,color="cyan", group = "Temperature") %>%
    
     addMarkers(data=Tucson, label = ~name, popup= ~paste(), group= "Cities Near the Most Observations")%>% 
     addMarkers(data=LA, label = ~name, popup= ~paste(), group= "Cities Near the Most Observations")%>%
     addMarkers(data=Brown, label = ~name, popup= ~paste(), group= "Cities Near the Most Observations")%>%
    
      addCircleMarkers(data=TV_obv_winter,~longitude, ~latitude, radius=.5,fillOpacity = 0.5, color = "grey",popup = ~paste("Turkey Vulture: Winter", "<br>", eventDate),
                   group = "Turkey Vulture Winter Observation")%>%
    
      addCircleMarkers(data=TV_obv_summer,~longitude, ~latitude, radius=.5,fillOpacity = 0.5, color = "purple", popup = ~paste("Turkey Vulture", "<br>", eventDate),
                   group = "Turkey Vulture: Observation")%>%
      addLayersControl(overlayGroups = c("Turkey Vulture Winter Observation", "Turkey Vulture: Observation", "Temperature", "Cities Near the Most Observations"),
    options = layersControlOptions(collapsed = FALSE)
      ) %>%
      addLegend(position = "bottomright", 
            colors = c("grey", "purple","cyan"), 
            labels = c("Turkey Vulture: Winter", "Turkey Vulture","Temperature"), 
            opacity = 1)%>%
      addLegend("bottomleft", title = "Elevation",
            pal = colorNumeric(palette = c("lightgreen", "green", "darkgreen", "yellow", "orange", "red"), domain = c(0, 2000)),
            values = c(0, 2000),
            labels = c("0-200m", "201-400m", "401-600m", "601-800m", "801-1000m", "1001-2000m"),opacity = 1) 
    ## Warning in validateCoords(lng, lat, funcName): Data contains 65 rows with
    ## either missing or invalid lat/lon values and will be ignored
    ## Warning in validateCoords(lng, lat, funcName): Data contains 29 rows with
    ## either missing or invalid lat/lon values and will be ignored
    ## Assuming "lng" and "lat" are longitude and latitude, respectively
    ## Assuming "lng" and "lat" are longitude and latitude, respectively
    ## Assuming "lng" and "lat" are longitude and latitude, respectively
    map


Provide appropriate legends to describe the data (2 pts). Describe the choices you made on the map design and representation I chose purple and grey to represent the Turkey Vulture observation because they’re cool colors that don’t blend in with the warm colors of the map and they’re colorblind friendly. I chose cyan for the temperature because it doesn’t blend in with the elevation colors and doesn’t hide the observation points allowing them to still be visible. The elevation colors I chose after setting up map as the colorsin the legion represent the one’s on the map the best. I also made it possible to hide each of the points and visuals so viewers had the option to only see what they need.