Finding the nearest date (but not the same date) in R

To find the nearest 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 the function to give me the nearest date different from the date itself. So, in this case, "2011-08-18." How can I change my code to get this? Thanks.

+4
source share
1 answer

Just remove dates that are equal from dist calculations and from the select operation:

  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" 
+3
source

All Articles