简体   繁体   English

从日期中提取财政年度

[英]Extract financial year from dates

I've several variables which i'm looking to organise by financial year (1 April to 31 March).我希望按财政年度(4 月 1 日至 3 月 31 日)组织几个变量。

library(lubridate)
StartDate <- ymd(c("2017-03-26", "2018-07-04", "2019-02-23", "2010-10-31", "1989-06-30"))

I have been able to extract the year and quarter from these dates, specifiying the fiscal start as month 4, using lubridates quarter function.我已经能够从这些日期中提取年份和季度,使用 lubridates 季度函数将财政开始指定为第 4 个月。 But i want the financial year variable to be in the format of 2017/18, 2018/19, etc.但我希望财政年度变量采用 2017/18、2018/19 等格式。

I also found the date2fy function, which works:我还找到了 date2fy 函数,它有效:

date2fy(StartDate)

but it's default is the austrailian financial year running from 1 July to 30 June and can't figure out how to change it to start from 1 April.但它的默认值是从 7 月 1 日到 6 月 30 日的澳大利亚财政年度,无法弄清楚如何将其更改为从 4 月 1 日开始。

I've written the below and it works, but is there any better/shorter method of doing it?我已经写了下面的内容并且它有效,但是有没有更好/更短的方法来做到这一点?

DEP$Start_Fin_Year <- as.numeric(format(DEP$StartDate, "%Y")) - (format(DEP$StartDate, "%m") <= "03")
library(stringr)
DEP$Start_Fin_Year2 <- str_sub(DEP$Start_Fin_Year,start=-2)
DEP$Start_Fin_Year2 <- as.numeric(DEP$Start_Fin_Year2)
DEP$Start_Fin_Year3 <- (DEP$Start_Fin_Year2 + 1)
DEP$Start_Fin_Year4 <- paste0(DEP$Start_Fin_Year, "/", DEP$Start_Fin_Year3)
tibble::tibble(StartDate = StartDate) %>% 
  dplyr::mutate(finstart = ymd(paste0(year(StartDate), "-04-01")),
                finyear = ifelse(StartDate >= finstart, year(finstart) + 1, year(finstart)))

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

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