Registration for R in 3 Months opens August 21. Get notified →

Mapping with R

# Highlight a Region in a Country with leaflet (03_04)

### Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

In this I used the function `st_touches()` from the {sf} package to extract the states that border Texas. The {sf} package contains several functions like this for detecting/extracting parts of an {sf} object that meet a specific geometric condition. Some examples include:

• `st_touches()` for testing if polygons share a border (that does not overlap)

• `st_overlaps()` for testing if polygons overlap

• `st_covers()` for testing if points belong to a polygon

It’s easiest to demonstrate how `st_covers()` works:

``st_covers(x, y, sparse = FALSE)``

This function will test if the features in x are covered by y. We set spare = FALSE because otherwise the function will return a complicated “sparse geometry predicate”, instead what we get back is a vector containing TRUE for covered parts of x and FALSE for uncovered parts.

With that in mind, here’s the code I showed again:

``us_contiguous[st_touches(texas_state, us_contiguous, sparse = FALSE),]``
1. `st_covers()` returns a vector of TRUE/FALSE for states from `us_contiguous` that touch `texas_state`. Let’s call this vector touching_predicate.

2. The code can now be read as follows, `us_contiguous[touching_predicate, ]`

3. This will return those rows from `us_contiguous` touch `texas_state`.

Unfortunately, there isn't a tidyverse-friendly way to work with these functions. The Spatial Data Operations chapter of Geocomputation with R provides more information about how to do these types of {sf} data manipulation.

## Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.

34 Lessons