Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Last active June 25, 2021 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavisVaughan/a77360b3dc195a183d631b5f1118182e to your computer and use it in GitHub Desktop.
Save DavisVaughan/a77360b3dc195a183d631b5f1118182e to your computer and use it in GitHub Desktop.
flexible-joins
library(dplyr)
x <- tibble(
a1 = c(1, 5, 7, 12),
a2 = c(4, 6, 11, 15)
)
y <- tibble(
b = c(2, 3, 1, 4, 6, 0, 14)
)
# Notice `y$b` doesn't have any values in [7, 11]
left_join(x, y, by = join_by(a1 <= b, a2 >= b))
#> # A tibble: 7 x 3
#> a1 a2 b
#> <dbl> <dbl> <dbl>
#> 1 1 4 2
#> 2 1 4 3
#> 3 1 4 1
#> 4 1 4 4
#> 5 5 6 6
#> 6 7 11 NA
#> 7 12 15 14
# To also see unmatched values in `y$b`
full_join(x, y, by = join_by(a1 <= b, a2 >= b))
#> # A tibble: 8 x 3
#> a1 a2 b
#> <dbl> <dbl> <dbl>
#> 1 1 4 2
#> 2 1 4 3
#> 3 1 4 1
#> 4 1 4 4
#> 5 5 6 6
#> 6 7 11 NA
#> 7 12 15 14
#> 8 NA NA 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment