The representation of year and month information in YYYYYMM format as an integer is often handy and a useful and efficient data structure. Adding a number of months to such a date is not quite catchy, however, since the date structure is to be retained. For example, 201201 - 2 [months] is expected to result in 201111 instead of 201199. AddMonthsYM does this job.

as.ym(x)
# S3 method for class 'ym'
as.Date(x, d = 1, ...)

# S3 method for class 'ym'
AddMonths(x, n, ...)

Arguments

x

a vector of integers, representing the dates in the format YYYYMM, to which a number of months has to be added. YYYY must lie in the range of 1000-3000, MM in 1-12.

d

the day to be used for converting a yearmonth to a date. Default is 1.

n

the number of months to be added. If n is negative the months will be subtracted.

...

further arguments (not used here).

Details

All parameters will be recyled if necessary. The therefore used function mapply will display a warning, if the longer argument is not a multiple of the length of the shorter one.

Value

a vector of class integer with the same dimension as x, containing the transformed dates.

Author

Andri Signorell <andri@signorell.net>, originally based on code by Roland Rapold

See also

AddMonths; Date functions, like Year, Month, etc.

Examples


Month(as.ym(202408))
#> [1] 8
Year(as.ym(202408))
#> [1] 2024

Year(as.Date("2024-12-05"))
#> [1] 2024
Year(as.ym(202412))
#> [1] 2024

Month(as.Date("2024-12-05"), fmt = "mm")
#> [1] Dec
#> 12 Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < ... < Dec
Month(as.ym(202412), fmt="mm")
#> [1] Dec
#> 12 Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < ... < Dec

AddMonths(201511, 5)
#> [1] "2522-02-20"

AddMonths(c(201511, 201302), c(5, 15))
#> [1] "2522-02-20" "2522-05-23"
AddMonths(c(201511, 201302), c(5, -4))
#> [1] "2522-02-20" "2520-10-23"