Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Created August 7, 2022 18:51
Show Gist options
  • Save DavisVaughan/2bd84b426d9924c0354bb415077a28e7 to your computer and use it in GitHub Desktop.
Save DavisVaughan/2bd84b426d9924c0354bb415077a28e7 to your computer and use it in GitHub Desktop.
@DavisVaughan
Copy link
Author

# pak::pak("tidyverse/dplyr")
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df1 <- tibble(
  id1 = 1:50,
  daily = as.Date("2019-01-25") + 0:49
)

df2 <- tibble(
  id2 = 1:3,
  monthly = seq(as.Date("2019-01-01"), as.Date("2019-03-01"), by = "month")
)

df1
#> # A tibble: 50 × 2
#>      id1 daily     
#>    <int> <date>    
#>  1     1 2019-01-25
#>  2     2 2019-01-26
#>  3     3 2019-01-27
#>  4     4 2019-01-28
#>  5     5 2019-01-29
#>  6     6 2019-01-30
#>  7     7 2019-01-31
#>  8     8 2019-02-01
#>  9     9 2019-02-02
#> 10    10 2019-02-03
#> # … with 40 more rows
#> # ℹ Use `print(n = ...)` to see more rows
df2
#> # A tibble: 3 × 2
#>     id2 monthly   
#>   <int> <date>    
#> 1     1 2019-01-01
#> 2     2 2019-02-01
#> 3     3 2019-03-01

left_join(
  df1,
  df2,
  by = join_by(preceding(daily, monthly))
)
#> # A tibble: 50 × 4
#>      id1 daily        id2 monthly   
#>    <int> <date>     <int> <date>    
#>  1     1 2019-01-25     1 2019-01-01
#>  2     2 2019-01-26     1 2019-01-01
#>  3     3 2019-01-27     1 2019-01-01
#>  4     4 2019-01-28     1 2019-01-01
#>  5     5 2019-01-29     1 2019-01-01
#>  6     6 2019-01-30     1 2019-01-01
#>  7     7 2019-01-31     1 2019-01-01
#>  8     8 2019-02-01     2 2019-02-01
#>  9     9 2019-02-02     2 2019-02-01
#> 10    10 2019-02-03     2 2019-02-01
#> # … with 40 more rows
#> # ℹ Use `print(n = ...)` to see more rows

Created on 2022-08-07 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment