Skip to content

Commit

Permalink
Merge pull request #485 from PedramNavid/master
Browse files Browse the repository at this point in the history
add fiscal_start to quarter when fiscal year doesn't begin in january
  • Loading branch information
vspinu committed Oct 22, 2016
2 parents 35cb3ea + 10d5974 commit aa43000
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
15 changes: 12 additions & 3 deletions R/accessors-quarter.r
Expand Up @@ -10,19 +10,28 @@ NULL
#' anything else that can be converted with as.POSIXlt
#' @param with_year logical indicating whether or not to include the quarter's
#' year.
#' @param fiscal_start numeric indicating the starting month of a fiscal year
#' @return numeric
#' @examples
#' x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31"))
#' quarter(x)
#' quarter(x, with_year = TRUE)
#' quarter(x, with_year = TRUE, fiscal_start = 11)
#' semester(x)
#' semester(x, with_year = TRUE)
#' @export
quarter <- function(x, with_year = FALSE) {
quarter <- function(x, with_year = FALSE, fiscal_start = 1) {
fs <- fiscal_start - 1
shifted <- seq(fs, 11 + fs) %% 12 + 1
m <- month(x)
quarters <- rep(1:4, each = 3)
q <- quarters[m]
if (with_year) year(x) + q/10
s <- match(m, shifted)
q <- quarters[s]
if (with_year) {
uq <- quarters[m]
inc_year <- q == 1 & uq == 4
year(x) + inc_year + q/10
}
else q
}

Expand Down
5 changes: 4 additions & 1 deletion man/quarter.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions tests/testthat/test-accessors.R
Expand Up @@ -104,6 +104,28 @@ test_that("months accessor extracts correct month",{

})

test_that("quarters accessor extracts correct quarter", {
poslt <- as.POSIXlt("2010-11-03 13:45:59", tz = "UTC", format
= "%Y-%m-%d %H:%M:%S")
posct <- as.POSIXct(poslt)
date <- as.Date(poslt)

expect_that(quarter(poslt), equals(4))
expect_that(quarter(poslt, with_year = TRUE), equals(2010.4))
expect_that(quarter(poslt, fiscal_start = 11), equals(1))
expect_that(quarter(poslt, with_year = TRUE, fiscal_start = -2 ), equals(2011.1))

expect_that(quarter(posct), equals(4))
expect_that(quarter(posct, with_year = TRUE), equals(2010.4))
expect_that(quarter(posct, fiscal_start = 11), equals(1))
expect_that(quarter(posct, with_year = TRUE, fiscal_start = -2 ), equals(2011.1))

expect_that(quarter(date), equals(4))
expect_that(quarter(date, with_year = TRUE), equals(2010.4))
expect_that(quarter(date, fiscal_start = 11), equals(1))
expect_that(quarter(date, with_year = TRUE, fiscal_start = -2 ), equals(2011.1))
})

test_that("years accessor extracts correct year",{
poslt <- as.POSIXlt("2010-02-03 13:45:59", tz = "UTC", format
= "%Y-%m-%d %H:%M:%S")
Expand Down

0 comments on commit aa43000

Please sign in to comment.