使用R Lubridate提取财政年度

6
我会创建几个日期。
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) 我收到以下错误消息:
错误信息为:

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


3
as.integer(quarter(x, with_year = TRUE, fiscal_start = 10)) 的意思是什么? - C. Braun
lubridate::year(x) 对我来说可以用。这是你要找的吗? - zack
lubridate::year(x) 用于获取日历年。我要找的是财政年度 - stackinator
2个回答

11

如果您不介意增加一步操作,您可以提取季度的前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
quarter() 的行为可能与预期不同,请参见此处 https://github.com/tidyverse/lubridate/issues/682 - oatmilkyway

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接