Add/subtract 6 months (bond time) in R using lubridate

大城市里の小女人 提交于 2019-11-27 12:26:19

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"

I just coded this out quickly, but I think it should work. I'm not sure if it's the most elegant solution, however.

# up = 1, down = -1
six.mo.mover<-function(date,up.or.down) {
  last.day <- month(date) != month(as.Date(date)+1) 
  if(last.day) {
    adj.date <- as.Date(date) - day(as.Date(date)-1) + up.or.down*months(6)
    adj.mo <- month(adj.date)
    if (adj.mo == 2) {
      dy <- 28 + leap_year(year(adj.date))
    }
    else {
      dy <- 31-(adj.mo-1)%%7%%2
    }
    adj.date + days(dy-1)
  } 
  else {
    as.Date(date)+up.or.down*months(6)
  }
}

NB: not debugged, so check it yourself and let me know.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!