Skip to content

Instantly share code, notes, and snippets.

@tbrittoborges
Forked from philippbayer/date_range_merge.R
Created February 12, 2019 16:03
Show Gist options
  • Save tbrittoborges/9fe3c9ce75eb967aea18caac2a5cae9b to your computer and use it in GitHub Desktop.
Save tbrittoborges/9fe3c9ce75eb967aea18caac2a5cae9b to your computer and use it in GitHub Desktop.
library(tidyverse)
library(lubridate) # for the days() function
library(fuzzyjoin) # for the fuzzy_left_join() function
climate <- read_tsv('./timetable.csv')
# date temperature
#1 2018-11-21 100
#2 2018-11-22 80
milk <- read_tsv('./milk.csv')
# date yield
#1 2018-11-22 150
# turn the characters of dates into proper Date objects
milk <- milk %>% mutate(date = as.Date(date, format = "%d/%m/%Y"))
climate <- climate %>% mutate(date = as.Date(date, format='%d/%m/%Y'))
# make a start and end range with plus/minus 7 days
climate$start <- climate$date - days(7)
climate$end <- climate$date + days(7)
# fuzzy left join on the range
fuzzy_left_join(
milk, climate,
by = c(
# left table: by date
# right table: by start and end
"date" = "start",
"date" = "end"
),
# say that date of left table has to be bigger or equal to start of right table
# say that date of left table has to be smalller or equal to end of right table
match_fun = list(`>=`, `<=`)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment