how to iterate over months in R?

Hi I currently have the following problem;

Every month i have to produce the following title (which is just a string), i'm looking for a more efficient way of doing this, here is how the titles work

for example here is the following titles per month - the rule is simple, it increments the starting month by 1 and the ending month by 1 each time, but this is based on the current month:

Here are examples:

Month October 2018, Title is = June To August

Month november 2018, Title is = July to September

Month December 2018, Title is = August to October

Month January 2019, Title is = September to November

So the next one in the sequence is going to be:

Month February 2019, Title is = October to December

Is there any way i can produce the next iteration in R? without hard coding as it needs to increment itself correctly

I would like to find a way of basically creating a sequence that uses the above format - but have to be careful when the iteration comes back as there is no 13th month instead it is month 1 (January)

any ideas?

You can use lubridate package (please ignore the spanish locale, this will work in English too)

paste(format(Sys.Date() %m-% months(1), "%B"), "to", format(Sys.Date() %m+% months(1), "%B"))
#> [1] "enero to marzo"
fake_date <- as.Date('2019-12-01')
paste(format(fake_date %m-% months(1), "%B-%Y"), "to", format(fake_date %m+% months(1), "%B-%Y"))
#> [1] "noviembre-2019 to enero-2020"

Created on 2019-02-12 by the reprex package (v0.2.1)


I love your solution, but I've a question.

%m+% increments the month by 1, and %m-% reduces it by 1. What does %B do?

Does it convert month index to full name or something similar?

It's just the format, it means the complete name of the month i.e. January, if you use %m it gives you the month as a number and so on

paste(format(Sys.Date() %m-% months(1), "%m"), "to", format(Sys.Date() %m+% months(1), "%b"))
#> [1] "01 to mar"

There are nice little table of the common date-character conversion formats: and
(Below are for

Code Value
%d Day of the month (decimal number)
%m Month (decimal number)
%b Month (abbreviated)
%B Month (full name)
%y Year (2 digit)
%Y Year (4 digit)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.