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.