R/financial-year.R

#' Financial year helpers
#'
#' These functions return allow you to select variables based on their names.
#' * `fye()`: returns the financial year ending
#' * `fyb()`: returns the financial year beginning
#'
#' @param x A date-time object
#'
#' @name financial_year_helpers
#'
#' @return A numeric value giving the financial year ending or beginning.
#'
#' @importFrom magrittr "%>%"
#'
#' @examples
#' require(lubridate)
#' x <- dmy("1/1/2015") + months(0:11)
#' fye(x)
#' # 2015 2015 2015 2015 2015 2015 2016 2016 2016 2016 2016 2016
NULL

#' @rdname financial_year_helpers
#' @export
fye <- function(x) {
  UseMethod("fye")
}

#' @export
fye.default <- function(x) {
  tibble::data_frame(x = x) %>%
    dplyr::mutate(Month = lubridate::month(x),
                  Year = lubridate::year(x)) %>%
    dplyr::mutate(Year = ifelse(lubridate::month(x) <= 6,
                                Year,
                                Year + 1)) %>%
    .$Year
}

#' @rdname financial_year_helpers
#' @export
fyb <- function(x) {
  UseMethod("fyb")
}

#' @export
fyb.default <- function(x) {
  tibble::data_frame(x = x) %>%
    dplyr::mutate(Month = lubridate::month(x),
                  Year = lubridate::year(x)) %>%
    dplyr::mutate(Year = ifelse(lubridate::month(x) <= 6,
                                Year - 1,
                                Year)) %>%
    .$Year
}



# TODO: see above todo
# fy_label <- functin(x) {
#   UseMethod("fy_label")
#   # TODO: This function will use fye and fyb to output an ordered factor with
#   # format YYYY-YYYY
# }
camroach87/myhelpr documentation built on May 13, 2019, 11:03 a.m.