I am trying to add a specified number of months to a yymm
formatted date. I'm having a hard time dealing with cases when mm exceeds 12. So, for example:
9109 (ie. 1991-Sept) + 17 months should yield 9302.
9103 + 3 months should yield 9106
Currently, I am trying to use modular arithmetic to obtain the additional months in yymm format, but this isn't working as well as hoped. I convert 17 months into 0105, but adding 0105 to 9109 leads to 9214, which is nonsensical.
Thank you for any help.
Here are several approaches. All also work if x is a vector.
1) as.yearmon Suggest storing your year/month data as yearmon objects. They are stored internally as year + fraction where fraction is 0 for January, 1/12 for February, ..., 11/12 for December and when printed show in a recognizable form.
Note that because x is numeric if we are in 2000 or 2001 then x does not have 4 digits so we need to zero fill as shown should such dates be in the input.
It's probably easier to just keep everything as yearmon objects but you could replace the last line with as.numeric(format(ym + 17/12, "%y%m"))
if you want the output in the same form as x
.
library(zoo)
x <- 9109
ym <- as.yearmon(sprintf("%04f", x), "%y%m")
ym + 17/12
## [1] "Feb 1993"
2) as.POSIXlt Another approach is to convert to POSIXlt and then add 17 to the months. This does not use any packages. We have returned a character string below but you can convert it to numeric using as.numeric
if you want it in exactly the same form as x
.
lt <- as.POSIXlt(sprintf("%04d01", x), format = "%y%m%d")
lt$mon <- lt$mon + 17
format(lt, "%y%m")
## [1] "9302"
3) modular arithmetic To use modular arithmetic convert it to months, add 17 and convert back. This does not use any packages.
months <- (12 * x %/% 100) + (x %% 100) - 1 + 17
100 * (months %/% 12) + months %% 12 + 1
## [1] 9302