Может использоваться скользящее соединение с использованием data.table.См. Также: https://www.r -bloggers.com / creation-data-table-Rolling-Joins /
Также решение, использующее решение base-R
data.table
library(data.table)
dates.df <- data.table(val=seq(1:121), dates = seq.Date(as.Date('2018-12-01'), as.Date('2019-03-31'), "days"))
monthly.df <- data.table(val=c(1,2,4,5), dates = c(as.Date('2018-12-14'), as.Date('2019-1-2'), as.Date('2019-2-3')))
setkeyv(dates.df,"dates")
setkeyv(monthly.df,"dates")
#monthly.df[,nearest:=(dates)][dates.df,roll = 'nearest'] #closest date
monthly.df[,nearest:=(dates)][dates.df,roll = Inf] #Closest _previous_ date
базовое решение R
dates.df <- zoo(data.frame(val=seq(1:121)), order.by = seq.Date(as.Date('2018-12-01'), as.Date('2019-03-31'), "days"))
monthly.df <- zoo(data.frame(val=c(1,2,4)), order.by = c(as.Date('2018-12-14'), as.Date('2019-1-2'), as.Date('2019-2-3')))
dates.df <- data.frame(val=dates.df$val,dates=attributes(dates.df)$index)
monthly.df <- data.frame(val=monthly.df$val,dates=attributes(monthly.df)$index)
min_distances <- as.numeric(dates.df$dates)- matrix(rep(as.numeric(monthly.df$dates),nrow(dates.df)),ncol=length(monthly.df$dates),byrow=T)
min_distances <- as.data.frame(t(min_distances))
closest <- sapply(min_distances,function(x)
{
w <- which(x==min(x[x>0]));
ifelse(length(w)==0,NA,w)
})
dates.df$closest_month <- monthly.df$dates[closest]
Результаты: data.table
> monthly.df[,nearest:=(dates)][dates.df,roll = Inf]
val dates nearest i.val
1: NA 2018-12-01 <NA> 1
2: NA 2018-12-02 <NA> 2
3: NA 2018-12-03 <NA> 3
4: NA 2018-12-04 <NA> 4
5: NA 2018-12-05 <NA> 5
---
118: 4 2019-03-27 2019-02-03 117
119: 4 2019-03-28 2019-02-03 118
120: 4 2019-03-29 2019-02-03 119
121: 4 2019-03-30 2019-02-03 120
122: 4 2019-03-31 2019-02-03 121
База результатов R
> dates.df[64:69,]
val dates closest_month
2019-02-02 64 2019-02-02 2019-01-02
2019-02-03 65 2019-02-03 2019-01-02
2019-02-04 66 2019-02-04 2019-02-03
2019-02-05 67 2019-02-05 2019-02-03
2019-02-06 68 2019-02-06 2019-02-03
2019-02-07 69 2019-02-07 2019-02-03