英文:
How to change date to nearest date in another date frame in R?
问题
date <- as.Date("2020-12-05")
date2 <- as.Date(ymd("2020-12-07"):ymd("2020-12-30"))
假设我有上述两个日期值
如何编写代码将date的值更改为date2中最接近的日期?即将date的值更改为2020-12-07。
谢谢
英文:
date <- as.Date("2020-12-05")
date2 <- as.Date(ymd("2020-12-07"):ymd("2020-12-30"))
Assuming I have the 2 above date values
How do I write code to change the value in date to its nearest counter part in date2? i.e. changing date value to 2020-12-07.
Thanks
答案1
得分: 1
计算date
和date2
之间的差异,并使用which.min()
索引这些差异。
date <- as.Date("2020-12-05")
date2 <- seq(as.Date("2020-12-07"), as.Date("2020-12-30"), by = "1 day")
date2[which.min(abs(date2 - date))]
# "2020-12-07"
请注意,如果存在平局(例如,存在早两天和晚两天的日期),这将返回首次出现的日期。根据@I_O的建议,您可以对date2
进行排序,以控制在这种情况下返回较早或较晚的日期:
# 返回较早的日期
date2_asc <- sort(date2)
date2_asc[which.min(abs(date2_asc - date))]
# 返回较晚的日期
date2_desc <- sort(date2, decreasing = TRUE)
date2_desc[which.min(abs(date2_desc - date))]
英文:
Compute differences between date
and date2
, and index using which.min()
of these differences.
date <- as.Date("2020-12-05")
date2 <- seq(as.Date("2020-12-07"), as.Date("2020-12-30"), by = "1 day")
date2[which.min(abs(date2 - date))]
# "2020-12-07"
Note in case of ties (eg, both a date two days earlier and two days later exist), this will return whichever occurs first. As suggested by @I_O, you can sort date2
to control whether the earlier or later date is returned in this case:
# to return earlier date
date2_asc <- sort(date2)
date2_asc[which.min(abs(date2_asc - date))]
# to return later date
date2_desc <- sort(date2, decreasing = TRUE)
date2_desc[which.min(abs(date2_desc - date))]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论