Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Fiscal Year with R Lubridate

Tags:

r

lubridate

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)

like image 464
stackinator Avatar asked Jun 05 '18 14:06

stackinator


2 Answers

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"
like image 143
camille Avatar answered Oct 06 '22 23:10

camille


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
like image 28
dlxx Avatar answered Oct 07 '22 00:10

dlxx