使用 R Lubridate 提取会计年度

Extract Fiscal Year with R Lubridate

我会创建几个日期。

library(lubridate)
x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31"))

我可以从这些 x 值中提取年份和季度。

quarter(x, with_year = TRUE, fiscal_start = 10)

[1] 2012.2 2012.3 2012.4 2013.1

但我似乎无法提取 just 财政年度。这行不通,但什么会呢?

year(x, with_year = TRUE, fiscal_start = 10)

我收到以下错误消息:

Error in year(x, with_year = TRUE, fiscal_start = 10) : unused arguments (with_year = TRUE, fiscal_start = 10)

如果您不介意额外的步骤,则可以提取季度的前 4 个字符以获取年份。

library(lubridate)

x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31"))

q <- quarter(x, with_year = TRUE, fiscal_start = 10)
q
#> [1] 2012.2 2012.3 2012.4 2013.1

fy <- stringr::str_sub(q, 1, 4)
fy
#> [1] "2012" "2012" "2012" "2013"
library(lubridate)
library(data.table)

fiscal_start_month = 10

x <- data.table(Dates = ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31")))
x[, Fiscal_Year := ifelse(month(Dates) >= fiscal_start_month, year(Dates) + 1, year(Dates))]

这会产生:

            Dates Fiscal_Year
1: 2012-03-26        2012
2: 2012-05-04        2012
3: 2012-09-23        2012
4: 2012-12-31        2013