首页 > 解决方案 > 使用 R 查找最接近的日期匹配行索引

问题描述

我需要从数据表中找到最接近日期匹配的索引,如下所示。

coldate:  (data table or data frame) 

     mon_dd
1: 2018-09-04
2: 2018-09-10
3: 2018-09-17
4: 2018-09-24
5: 2018-10-01
6: 2018-10-08
7: 2018-10-15
8: 2018-10-22
9: 2018-10-29

x = as.Date("2018-09-25")

我使用以下代码,但它给了我一个错误,如下所示。

which.min(abs(x-coldate[,"mon_dd"]))

Error: 
Error in x - coldate[, "mon_dd"] : 
  non-numeric argument to binary operator

有人可以帮我解决这个问题吗?

谢谢。

标签: rdateindexingfind

解决方案


df<-c(as.Date("2018-09-04"),
           as.Date("2018-09-10"),
           as.Date("2018-09-17"),
           as.Date("2018-09-24"),
           as.Date("2018-10-01"),
           as.Date("2018-10-08"),
           as.Date("2018-10-15"),
           as.Date("2018-10-22"),
           as.Date("2018-10-29"))

x = as.Date("2018-09-25")

which.min(abs(df-x))
   [1] 4

假设您的数据是日期格式,这应该会给您所需的答案..


推荐阅读