Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

r - Add (subtract) months without exceeding the last day of the new month

I am looking to add and subtract six months (bond time) reliably with lubridate.

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

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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...