向量中给定日期的最接近日期 [英] Closest date in a vector to a given date

查看:97
本文介绍了向量中给定日期的最接近日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定日期的向量中标识最接近的日期。假设我有以下日期向量(带有5个随机日期):

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"));

现在,我想找到最接近 x = as.Date的日期。 ( 2013-10-01)

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

这是我的代码:

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

结果应为4,因为日期 2013-09-12 是最接近的日期。但是,我有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?

推荐答案

您错过了 abs 处理负值:

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

这篇关于向量中给定日期的最接近日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆