Closest date in a vector to a given date
The which.closest()
function from the birk
package is a simple option.
coldate= as.Date(c("2013-08-03", "2013-09-04", "2013-09-08", "2013-09-12", "2013-11-01"))
x = as.Date("2013-10-01")
which.closest(coldate, x)
[1] 4
See also the which.min
function:
R> which.min(abs(x-coldate))
[1] 4
you miss an abs
to take care of negative values:
which(abs(coldate-x) == min(abs(coldate - x)))
[1] 4