typestar

Joining on different keys in R

join_by handles renamed keys, inequality joins and rolling matches.

library(dplyr)

runs <- tibble(language = c("r", "python"), tpm = c(96, 104))
labels <- tibble(lang = c("r", "python"), label = c("R", "Python"))

print(left_join(runs, labels, by = join_by(language == lang)))

bands <- tibble(low = c(0, 90, 100), high = c(90, 100, Inf),
                band = c("slow", "good", "fast"))
print(left_join(runs, bands, by = join_by(between(tpm, low, high))))

events <- tibble(at = c(2, 8), value = c("a", "b"))
settings <- tibble(at = c(1, 5), theme = c("light", "dark"))
print(left_join(events, settings, by = join_by(closest(at >= at))))

How it works

  1. join_by(a == b) joins columns with different names.
  2. An inequality in join_by gives a range join.
  3. closest() is the rolling join, for nearest-time matching.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
556
Tokens
204
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 117 seconds.

Type this snippet

Step 2 of 4 in Joining, step 22 of 27 in dplyr.

← Previous Next →