2
votes

I'm hoping to retrieve the month number from a fiscal year that starts in November (i.e. the first day of the fiscal year is November 1st). The following code provides my desired output, borrowing the week_start syntax of lubridate::wday, where year_start is analogous to week_start:

library('lubridate')
dateToRetrieve = ymd('2017-11-05')
#output: [1] "2017-11-05"
monthFromDate = month(dateToRetrieve, year_start=11)
#output: [1] 1

Since this functionality doesn't yet exist, I'm looking for an alternative solution that provides the same output. Adding period(10, units="month") to each date does not work because the length of different months leads to issues translating between months (e.g. March 31st minus a month = February 31st, which doesn't make sense).

I checked a somewhat similar question on the lubridate github here, but didn't see any solutions. Does anyone have an idea that will provide my desired functionality?

Many thanks,

2

2 Answers

2
votes

1) lubridate Below x can be a character vector or a Date vector:

x <- "2017-11-05" # test data
(month(x) - 11) %% 12 + 1
## [1] 1

2) Base R To do this with only base R first calculate the month number giving mx as shown and then perform the same computation:

mx <- as.POSIXlt(x)$mon + 1
(mx - 11) %% 12 + 1
## [1] 1
1
votes

It is a not pretty way... but you could create a vector range of months starting at November, call the full month of the date object, then match the two objects together to get the vector position.

suppressPackageStartupMessages(library('lubridate'))

x <- format(ISOdate(2004,1:12,1),"%B")[c(11,12,1:10)]

match(as.character(month(ymd('2017-11-05'), label = TRUE, abbr = FALSE)), x)
#> [1] 1
match(as.character(month(ymd('2017-01-15'), label = TRUE, abbr = FALSE)), x)
#> [1] 3
match(as.character(month(ymd('2017-05-01'), label = TRUE, abbr = FALSE)), x)
#> [1] 7