I have two data frames, a price dataset and a survey dataset, that I need to join on the closest date. The dates don't exactly match, and I need the price dataset to match on the closest date in the survey dataset. A previous question that I asked here on this was very helpful in giving me a an answer as to how to match on the closest date. However, I've since realized that I also need to join the data sets on region, as well as the closest date. I know how to join on closest date, I know how to join on region, but I unfortunately do not know how to join on the closest date and the exact same region.
Here's some example code and what I've been trying
#generating sample dataset
set.seed(1234)
price <- data.frame(region = sample(LETTERS[1:3],15,replace = TRUE), price = rnorm(15),price_date=sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 15))
survey <- data.frame(region = sample(LETTERS[1:3],15,replace = TRUE), survey_date=sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 15))
#this works to join on the closest date, however, the regions don't match, which is a problem
library(data.table)
setDT(price)
setDT(survey)
join <- price[survey,on=.(price_date=survey_date),roll="nearest"]
Basically what I want to do is match the date/region observation from price to the closest date, same region observation in survey, and I'm not really sure as to how to do this. Would appreciate any help.