用R Lubridate提取财政年度

时间:2018-06-05 14:38:20

标签: 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

但我似乎无法提取只是财政年度。这不起作用,但会是什么?

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

我收到以下错误消息:

  

年份错误(x,with_year = TRUE,fiscal_start = 10):         未使用的参数(with_year = TRUE,fiscal_start = 10)

2 个答案:

答案 0 :(得分:4)

如果你不介意另外一步,你可以提取你宿舍的前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"

答案 1 :(得分:3)

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