在R中找到最接近的日期(但不是相同的日期)

时间:2013-03-05 22:52:41

标签: r

为了找到最近的日期,我有:

closestDate <- function(searchDate, dateList, roundDown=FALSE) {
              as.Date(sapply(as.Date(searchDate), function(x){
                dist <- abs(x - as.Date(dateList))
                closest <- dateList[which(min(dist) == dist)]
                return(ifelse(roundDown, min(closest), max(closest)))
              }), origin="1970-1-1")
            }

何时:

> nonNAdays
[1] "2011-08-15" "2011-08-18" "2011-08-19"

我明白了:

> closestDate('2011-08-15', nonNAdays)
[1] "2011-08-15"

我希望函数能够给出除日期之外最接近的日期。所以在这种情况下,“2011-08-18”。如何更改我的代码才能获得此代码? 感谢。

1 个答案:

答案 0 :(得分:3)

只需从dist计算和选择操作中删除 相等的日期:

  closestDate <- function(searchDate, dateList, roundDown=FALSE) {
           as.Date(sapply(as.Date(searchDate), function(x){
             dist <- abs(x - as.Date(dateList[dateList != searchDate]))
             closest <- dateList[dateList != searchDate][which(min(dist) == dist)]
             return(ifelse(roundDown, min(closest), max(closest)))
           }), origin="1970-1-1")
         }
 nonNAdays <- c("2011-08-15", "2011-08-18", "2011-08-19")
  closestDate('2011-08-15', nonNAdays)
#[1] "2011-08-18"