library(here)
library(tidyverse)
library(stars)
library(sf)
library(tmap)
Read in Vector Data
<- st_read(here::here("data", "week2-discussion", "Colombia", "Colombia.shp"))
col
<- st_read(here::here("data", "week2-discussion", "RDLINE_colombia", "RDLINE_colombia.shp"))
roads
<- readr::read_csv(here::here("data", "week2-discussion", "dataves.csv")) %>%
aves ::as_tibble() %>%
dplyr::rename(long = decimal_longitude) %>%
dplyr::mutate(lat = decimal_latitude) %>%
dplyrst_as_sf(coords = c("long", "lat"), crs = 4326)
Check Class and Geometry Type
class(col)
class(roads)
class(aves)
unique(st_geometry_type(col))
unique(st_geometry_type(roads))
unique(st_geometry_type(aves))
Select Macro Region of Interest
<- col %>%
col_andean # Set categorical "levels" in attribute N1_MacroBi (subregions of Colombia)
::mutate(N1_MacroBi = as.factor(N1_MacroBi)) %>%
dplyr# Subset to Andean region of Colombia
::filter(N1_MacroBi == "Andean") dplyr
tm_shape(col_andean) +
tm_polygons() +
tm_layout(main.title = "Andean Region of Colombia",
main.title.size = 1)
Play with Coordinate Reference System
# Print the CRS of each spatial object
st_crs(col)
st_crs(roads)
st_crs(aves)
# Print units of each CRS
st_crs(col)$units
st_crs(roads)$units
st_crs(aves)$units
There are several ways to extract the longitude and latitude from the geometry
column.
purr
Approach
<- aves %>%
aves_df_purrr # Extract lat & long from geometry column
mutate(lon = unlist(purrr::map(aves$geometry, 1)), # longitude = first component (x)
lat = unlist(purrr::map(aves$geometry, 2))) %>% # latitude = second component (y)
st_drop_geometry() # Remove geometry column now that it's redundant
st_coordinates
Approach
<- aves %>%
aves_df_st_coords ::mutate(lon = sf::st_coordinates(.)[,1],# Assign first matrix item to "lon"
dplyrlat = sf::st_coordinates(.)[,2]) %>% # Assign second matrix item to "lat"
st_drop_geometry() # Remove geometry column now that it's redundant
Next, convert to sf
object again.
st_as_sf
Approach
<- aves %>%
aves_df_purrr st_as_sf(coords = c("lon", "lat"), crs = 4326)
Bring All Vector Data Types Together
# Boolen check if CRS match between 2 datasets
st_crs(col) == st_crs(roads)
# Transform bird data into same CRS as other Colombia data
<- st_transform(aves, crs = st_crs(col)) aves
# Simple plot with all 3 data layers
tm_shape(col) +
tm_polygons() +
tm_shape(roads) +
tm_lines() +
tm_shape(aves) +
tm_dots() +
tm_layout(main.title = "Colombia ecoregions, roads,\nand bird observations",
main.title.size = 1)