Author

Carolyn Koehn

Read in the libraries we need

Code
library(sf)
library(tigris)

Get a sf object of ID counties (from the tigris package)

Code
id.cty <- counties(state = "ID")

Check CRS of object

Code
st_crs(id.cty)$input
[1] "NAD83"

Unary predicates

Code
st_is_longlat(id.cty)
[1] TRUE
Code
st_is_valid(id.cty)[1:5]
[1] TRUE TRUE TRUE TRUE TRUE
Code
all(st_is_valid(id.cty))
[1] TRUE

Get some data for binary operations

Code
library(tidyverse)

id <- states(progress_bar=FALSE) %>% 
  filter(STUSPS == "ID")
or <- states(progress_bar=FALSE) %>% 
  filter(STUSPS == "OR")
ada.cty <- id.cty %>% 
  filter(NAME == "Ada")

Try some predicates

Code
st_covers(id, ada.cty)
Sparse geometry binary predicate list of length 1, where the predicate
was `covers'
 1: 1
Code
st_covers(id, ada.cty, sparse = FALSE)
     [,1]
[1,] TRUE
Code
st_within(ada.cty, or)
Sparse geometry binary predicate list of length 1, where the predicate
was `within'
 1: (empty)
Code
st_within(ada.cty, or, sparse=FALSE)
      [,1]
[1,] FALSE

Unary measures

Code
st_area(id)
2.15994e+11 [m^2]
Code
st_area(id.cty)[1:5]
Units: [m^2]
[1] 2858212132 3380630278 1459359818 1726660462 1223521586
Code
st_dimension(id.cty)[1:5]
[1] 2 2 2 2 2

Binary measure (distance)

Code
kootenai.cty <- id.cty %>% 
  filter(NAME == "Kootenai")
st_distance(kootenai.cty, ada.cty)
Units: [m]
         [,1]
[1,] 396433.8
Code
st_distance(id.cty)[1:5, 1:5]
Units: [m]
         [,1]     [,2]     [,3]     [,4]     [,5]
[1,]      0.0 467635.7 277227.0 132998.0      0.0
[2,] 467635.7      0.0 319706.4 656056.0 514306.9
[3,] 277227.0 319706.4      0.0 377105.4 336146.8
[4,] 132998.0 656056.0 377105.4      0.0 133045.5
[5,]      0.0 514306.9 336146.8 133045.5      0.0

Practice exercise code:

Code
# Part 1
owyhee.cty <- id.cty %>% 
  filter(NAME == "Owyhee")

# Part 2
st_within(owyhee.cty, id)
Sparse geometry binary predicate list of length 1, where the predicate
was `within'
 1: 1
Code
st_touches(owyhee.cty, or)
Sparse geometry binary predicate list of length 1, where the predicate
was `touches'
 1: 1
Code
# Part 3
st_bbox(owyhee.cty)
      xmin       ymin       xmax       ymax 
-117.02701   41.99612 -115.03751   43.68080 
Code
st_bbox(or)
      xmin       ymin       xmax       ymax 
-124.70354   41.99208 -116.46326   46.29910 

Challenge code:

Code
# Calculate distances between all counties
cty.dist <- st_distance(id.cty)

# Label rows and columns of matrix
colnames(cty.dist) <- id.cty$NAME
rownames(cty.dist) <- id.cty$NAME

# Find where the maximum value is
which(cty.dist == max(cty.dist), arr.ind = TRUE)
         row col
Boundary  40   4
Franklin   4  40
Code
# Locate the counties at the row numbers returned by which
# Needed if you don't label the rows and columns
id.cty$NAME[c(4, 40)]
[1] "Franklin" "Boundary"

Whiteboard notes