Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest date in a vector to a given date [duplicate]

Tags:

I would like to identify the closest date in a vector of given date. Let's say I have the following date vector (with 5 random dates):

coldate= as.Date(c("2013-08-03", "2013-09-04", "2013-09-08", "2013-09-12", "2013-11-01")); 

Now, I want to find the closest date to x = as.Date("2013-10-01") inside this vector.

Here is my code :

> which((coldate-x) == min(coldate-x))   [1] 1 

The result should be 4, since the date "2013-09-12" is the closest. But, I have 1... What's wrong in my code?

like image 627
Henri Avatar asked Feb 28 '13 11:02

Henri


1 Answers

you miss an abs to take care of negative values:

which(abs(coldate-x) == min(abs(coldate - x))) [1] 4 
like image 105
Arun Avatar answered Oct 21 '22 07:10

Arun