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.
source share