R / CHAPTER 09

Keyed alignment and join cardinality

Intermediate

Align records by keys rather than by incidental row positions.

By the end of this chapter

  • Use match to align a lookup
  • Detect duplicated lookup keys
  • Distinguish first-match lookup from all-match joins

The idea

Two tables can describe the same entities in different row orders. Combining their columns by position silently creates incorrect records unless alignment is guaranteed. Match returns the first position of each requested key in a lookup vector, allowing the result to follow the request order. An absent key yields NA by default and needs a stated missing-key policy.

First-match behavior is not the same as a relational join. Duplicate lookup keys make match choose only the first occurrence, while an all-match join may multiply rows. Validate lookup uniqueness when the domain promises one value per key. Test reordered keys, duplicates, and missing keys; checking only a perfectly aligned example cannot establish that the join answers the intended question.

R example
ids <- c("b","a","x")
lookup <- c("a","b")
values <- c(10,20)
cat(values[match(ids,lookup)], sep=",")
cat("\n")
Result
20,10,NA

Match reorders values into request order and preserves the missing request as NA.

Try it yourself

Align prices to requested product IDs, rejecting duplicated lookup IDs.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A lookup promises one row per ID. What should be checked before match?