Extract Fiscal Year with R Lubridate

独自空忆成欢 提交于 2019-11-28 09:14:00

问题


I'll create several dates.

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

I can extract the year and quarter from these x values.

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

[1] 2012.2 2012.3 2012.4 2013.1

But I can't seem to extract just the fiscal year. This doesn't work, but what will?

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

I receive the following error message:

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


回答1:


If you don't mind an additional step, you could then extract the first 4 characters of your quarters to get just the years.

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"



回答2:


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))]

This produces:

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


来源:https://stackoverflow.com/questions/50702804/extract-fiscal-year-with-r-lubridate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!