简体   繁体   English

使用lubridate检索会计年度的月数

[英]Retrieving month number in fiscal year using lubridate

I'm hoping to retrieve the month number from a fiscal year that starts in November (ie the first day of the fiscal year is November 1st). 我希望从11月开始的会计年度中检索月份号(即会计年度的第一天是11月1日)。 The following code provides my desired output, borrowing the week_start syntax of lubridate::wday , where year_start is analogous to week_start : 以下代码借用lubridate::wdayweek_start语法,提供了我想要的输出,其中year_start类似于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 (eg March 31st minus a month = February 31st, which doesn't make sense). 在每个日期上添加period(10, units="month")无效,因为不同月份的长度会导致月份之间转换的问题(例如3月31日减去一个月= 2月31日,这没有意义)。

I checked a somewhat similar question on the lubridate github here , but didn't see any solutions. 我检查了lubridate github上有点类似的问题在这里 ,但没有看到任何解决方案。 Does anyone have an idea that will provide my desired functionality? 有人能提供我想要的功能吗?

Many thanks, 非常感谢,

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. 这不是一个好方法...但是您可以创建一个从11月开始的月份的向量范围,调用日期对象的完整month ,然后将两个对象match在一起以获取向量位置。

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

1) lubridate Below x can be a character vector or a Date vector: 1)lubridate下面x可以是字符向量或一个Date向量:

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: 2)基数R要仅使用基数R来执行此操作,请首先计算给出mx的月份数,如图所示,然后执行相同的计算:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM