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)

library(lubridate)
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)

2 Likes

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"
3 Likes

There are nice little table of the common date-character conversion formats:
https://www.statmethods.net/input/dates.html and
https://www.stat.berkeley.edu/~s133/dates.html
(Below are for as.date())

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)
3 Likes

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.