我想传递一个日期向量,并且已经从(部分匹配)日期的第二个向量中返回了最接近的日期。

以下函数可以满足我对单个日期的要求,但是我无法弄清楚如何将其推广到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

有人可以帮忙吗?

最佳答案

现在,以该示例为例,只需处理小于一种情况或大于另一种情况的日期子集,此时将检查特定的目标。

closestDt <- function(searchDate, dateList, roundDown=FALSE)
     as.Date( sapply( searchDate , function (x) if( roundDown ){
                max( dateList[ dateList <= x ] ) } else {
                min( dateList[ dateList >= x])  }
           ), "1970-01-01")

关于r - Vectorise查找最接近的日期函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13946614/

10-12 12:39
查看更多