Chapter exercise: Joins: Attribute and Spatial
Matching Tables by Name and by Place
This exercise goes with Chapter 15, Joins: Attribute and Spatial. It builds on the tidyverse, tmap, and coordinate systems exercises. It should take you about one hour. Read this whole section before you start.
Save it in a new folder called joins-exercise inside your geog215 folder, open it in RStudio, and work through it from top to bottom. Everything on this page is also at the top of the file.
Purpose
Skills you’ll practice. By the end of this exercise you will be able to:
- Combine two tables with
inner_join(),left_join(),right_join(), andfull_join(), and predict how many rows each returns. - Name the key with
join_by(), including when the key columns have different names. - Find the rows that didn’t match with
anti_join(), and fix a key that doesn’t match. - Describe the cardinality of a relationship.
- Join by location with
st_join(), and count the points in each polygon with a summarized join. - Find the nearest feature with a distance join, after projecting both layers.
Knowledge you’ll gain. You’ll attach Census populations to North Carolina cities, map how median income changed across the states, find the London boroughs with the most bike-share stations, and find the nearest airport to ten North Carolina cities.
Why this matters. Data almost never arrives in one table. Census counts come without boundaries, boundaries come without the counts, and points such as schools or crimes need to be matched to the neighborhood they fall in. Joining is how you’ll bring your final project’s data together. A join that silently drops or duplicates rows is one of the most common hidden errors in data analysis, so checking the row count before and after every join is a habit worth building now.
Task
Work through Parts 1 to 7 in order, top to bottom. In each part:
- Read the short explanation, then do each step marked with a bullet (•).
- Wherever you see
___, replace it with the missing code before you run the chunk. A chunk with___in it won’t run. - Before you run each join, predict how many rows it will return. Then run it and check.
- Answer each question (Q1, Q2, …) in a sentence or two of Markdown, where it says Your answer here.
| Part | What you’ll do | About |
|---|---|---|
| 1 | Set up your file and load the data | 3 min |
| 2 | Four kinds of join on two small tables | 12 min |
| 3 | Join income data to state boundaries | 10 min |
| 4 | When names don’t match | 7 min |
| 5 | Spatial joins: which borough is each station in? | 13 min |
| 6 | Distance joins: the nearest airport | 10 min |
| 7 | Reflect, knit, and turn in | 5 min |
Turn in your .Rmd file and your knitted .html file on Canvas.
Criteria for success
Use this checklist before you turn your work in. Each item matches a row of the rubric below.
| Criterion | Full credit | Partial credit | No credit |
|---|---|---|---|
| Knits (2 pts) | Knits to HTML with every map showing | Knits, but some chunks have errors | Doesn’t knit, or no HTML turned in |
| Join code (5 pts) | Every blank filled in correctly; right join type and key each time | Most correct | Many blanks missing or wrong |
| Questions (9 pts) | Q1 to Q11 answered with row counts, names, and reasons | Some answers missing, wrong, or without reasons | Most answers missing |
| Maps (2 pts) | Both maps finished with title, legend title, and credits | Labels missing | Maps missing |
| Style (1 pt) | Pipe for chains, join_by() for keys, no install.packages() |
Several problems | |
| Reflection (1 pt) | All three answered | Missing |
What a good answer looks like. Here is a question, a weak answer, and a strong one.
Question: Why did the join return fewer rows than the first table?
Weak answer: “Some rows were dropped.”
Strong answer: “
inner_join()keeps only rows with a match in both tables.us_stateshas the lower 48 states and DC, so Alaska and Hawaii inus_states_dfhad no match and were dropped: 51 rows became 49.anti_join()lists them.”
The strong answer names the join type, says which rows were lost and why, gives the counts, and shows how to check.
IMPORTANT! Save often. Before you knit, choose Run > Restart R and Run All Chunks to make sure every chunk works from a fresh start.
GEOID with
left_join().
A family of R packages (including dplyr,
ggplot2, and readr) for reading,
cleaning, reshaping, summarizing, and plotting data, all designed to
work together.
An R package for making thematic maps quickly, with sensible defaults.
The rules that tie coordinates to places on the Earth, including how the
round Earth is flattened onto a map (the projection). Layers must share
a coordinate system before you can combine them.
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
How many rows in one table can match a row in another: one-to-one,
one-to-many, many-to-one, or many-to-many.
A closed shape that represents an area, such as a county, a lake, or a
census tract.
A spatial join that aggregates all the matching features, such as
counting the schools in each county.
The middle value when values are sorted, so half are above and half
below. Unlike counts, medians can’t be added across areas.
A block of R code inside an R Markdown file, starting with
```{r} and ending with three backticks.
A simple way of formatting plain text: # for headings,
*italic*, **bold**, and - for
list items.
A join that matches features by their location, such as attaching to
each point the polygon it falls inside. st_join() in R.
To build an R Markdown file into a finished document (HTML, PDF, or
Word). Knitting reruns every code chunk from the top in a fresh R
session.
A note for people that R ignores. In R, a comment starts with
#.
A method for flattening the curved graticule onto a flat map. Every
projection distorts shape, area, distance, or direction.
A join that keeps every row of the second (right) table.
right_join() in dplyr.
The operator |>, which passes the result on its left as
the first argument of the function on its right. Read it as “and then.”