stackinator
stackinator

Reputation: 5819

Extract Fiscal Year with 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)

Upvotes: 6

Views: 6966

Answers (2)

dlxx
dlxx

Reputation: 41

df <- data.frame(x)
fiscal_start = 10

# with base R
df$fy <- ifelse(month(df$x) >= fiscal_start, year(df$x) + 1, year(df$x))

# or with dplyr:
dplyr::mutate(df, fy = ifelse(month(x) >= fiscal_start, year(x) + 1, year(x)))

This produces:

           x   fy
1 2012-03-26 2012
2 2012-05-04 2012
3 2012-09-23 2012
4 2012-12-31 2013

Upvotes: 4

camille
camille

Reputation: 16842

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"

Upvotes: 12

Related Questions