如何在R中将日期更改为另一个日期框架中的最近日期?

huangapple go评论54阅读模式
英文:

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 &lt;- as.Date(&quot;2020-12-05&quot;)

date2 &lt;- as.Date(ymd(&quot;2020-12-07&quot;):ymd(&quot;2020-12-30&quot;)) 

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

计算datedate2之间的差异,并使用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 &lt;- as.Date(&quot;2020-12-05&quot;)
date2 &lt;- seq(as.Date(&quot;2020-12-07&quot;), as.Date(&quot;2020-12-30&quot;), by = &quot;1 day&quot;)

date2[which.min(abs(date2 - date))]
# &quot;2020-12-07&quot;

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 &lt;- sort(date2)
date2_asc[which.min(abs(date2_asc - date))]

# to return later date
date2_desc &lt;- sort(date2, decreasing = TRUE)
date2_desc[which.min(abs(date2_desc - date))]

huangapple
  • 本文由 发表于 2023年5月30日 12:03:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定