我想传入一个日期向量,并从第二个(部分匹配的)日期向量中返回最接近的日期。
以下函数可以满足我对单个日期的要求,但是我无法弄清楚如何将其推广到searchDate
日期向量的情况。
closestDate <- function(searchDate, dateList, roundDown=FALSE){
if (roundDown) {
dist2date <- as.Date(dateList) - as.Date(searchDate)
closest <- which(max(dist2date[dist2date<=0]) == dist2date)
} else {
dist2date <- as.Date(dateList) - as.Date(searchDate)
closest <- which(min(dist2date[dist2date>=0]) == dist2date)
}
return(dateList[closest])
}
dateSeq <- seq(as.Date("2011-01-01"), as.Date("2012-12-19"), by='day')
oddDates <- dateSeq[as.logical(1:length(dateSeq) %%2)]
closestDate('2012-12-14', oddDates)
[1] "2012-12-15"
miscDatesLong <- rep(c('2012-12-14', '2012-12-16', '2012-12-18'), 100 )
closestDate(miscDatesLong, oddDates)
closestDate(miscDatesLong, oddDates)
[1] "2012-12-15" "2012-12-17" "2012-12-19"
Warning message:
In unclass(time1) - unclass(time2) :
longer object length is not a multiple of shorter object length
有人可以帮忙吗?