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

假如想象 提交于 2019-12-03 15:58:01

问题


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?


回答1:


you miss an abs to take care of negative values:

which(abs(coldate-x) == min(abs(coldate - x)))
[1] 4



回答2:


See also the which.min function:

R> which.min(abs(x-coldate))
[1] 4



回答3:


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


来源:https://stackoverflow.com/questions/15133815/closest-date-in-a-vector-to-a-given-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!