【问题标题】:Find closest date matching row index using R使用 R 查找最接近的日期匹配行索引
【发布时间】:2018-09-21 15:33:03
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

  • which.min(abs(df$mon_dd - x)) 假设您的df$mon_dd 属于Date 类,如果不是先由df$mon_dd <- as.Date(df$mon_dd) 转换它
  • 谢谢。在我将它转换为日期类后它起作用了。

标签: r date indexing find


【解决方案1】:
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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2013-05-08
    • 2020-02-23
    • 2019-04-28
    • 2020-06-26
    相关资源
    最近更新 更多