使用lubridate在R中添加/减去6个月(键合时间) [英] Add/subtract 6 months (bond time) in R using lubridate

查看:110
本文介绍了使用lubridate在R中添加/减去6个月(键合时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用lubridate可靠地增加和减少六个月.

I am looking to add and subtract six months reliably with lubridate.

例如,将12/31/2014加六个月应得出6/30/2015, 并添加到2/28/2014应该会导致8/31/2014

For example, adding six months to 12/31/2014 should result in 6/30/2015, and adding to 2/28/2014 should result in 8/31/2014

as.Date("2014-12-31") + months(6)的问题在于它会产生一个NA.另外,第二个结果是2014年8月28日,因为它不仅会在该月中添加6个月,然后知道该月的结束日期取决于该月.

The issue with as.Date("2014-12-31") + months(6), is that it yields an NA. Alternatively, the second result is 8/28/2014 because it doesn't just add 6 months to the month and then know where the day should end up dependent upon the month.

有什么方法可以快速纠正此问题?目前,我正在构建一个基本上使用开关并每月考虑的功能,但这很长,我也遇到了问题.

Is there any way to quickly correct this? At the moment, I am building a function to basically use a switch and consider each month, but this is very long and I am having problems with it as well.

谢谢!

推荐答案

lubridate函数%m+%在这里可能有用:

The lubridate function %m+% may be useful here:

在日期中添加和减去月份,但不超过新月份的最后一天

Add and subtract months to a date without exceeding the last day of the new month

as.Date("2014-12-31") %m+% months(6)
# [1] "2015-06-30"

要处理第二种情况,您需要使用ceiling_date舍入到最近的月份,并使用days减去一天.

To also handle the second case, you will need to round up to nearest month using ceiling_date, and subtract one day using days.

ceiling_date(as.Date("2014-02-28") %m+% months(6), unit = "month") - days(1)
# [1] "2014-08-31"

这篇关于使用lubridate在R中添加/减去6个月(键合时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆