4

To find the closest date, I have:

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")
            }

When:

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

I get:

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

I would like for the function to give me the closest date other than the date itself. So in this case, "2011-08-18". How can I alter my code to get this? Thanks.

4

1 回答 1

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"
于 2013-03-05T23:00:30.707 回答