r - 使用 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
有人可以帮我解决这个问题吗?
谢谢。
解决方案
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
假设您的数据是日期格式,这应该会给您所需的答案..
推荐阅读
- javascript - “使用 Apple 登录”的问题 - 当我在 Web 应用程序上使用“使用 Apple 登录”按钮时,Apple 徽标未显示
- lisp - 如何在 clisp 中准确使用“cl-position”功能?
- linux - 显示屏幕的完整历史记录
- c# - 如何使刚体 2D 沿用户滑动的方向移动?
- android - 类型可能只包含一个@Inject 错误,有什么问题?
- javascript - 包含要转换的特殊十六进制的字符串
- javascript - 如何加深html表格中重叠单元格的颜色
- java - 如何使用java进行子字符串和连接
- python - 您能否在使用模板化 SQL 查询时简化查询
- ios - iPhone/iPad 上的谷歌浏览器不支持下载 csv 文件然后将其保存到我的设备