#' Season year adjustment
#'
#' When grouping data by season and year, creates a new variable for year with
#' Summer years switched to financial year ending. Other years are left as
#' calendar year.
#'
#' This prevents Summer from being incorrectly grouped. E.g. if grouping summer
#' months in 2015, January 2015, February 2015 and December 2015 will be grouped
#' together which is not useful. Rather, we would want December 2014 to be
#' included so that consecutive months are grouped.
#'
#' @param x A date-time object.
#' @param shoulder Logical. If TRUE only Summer and Winter are are defined to
#' include shoulder months. So summer will include October, November,
#' December, January, February, March and Winter will include April, May,
#' June, July, August, September. This results in financial year ending being
#' calculated for October and November as well as the other summer months.
#'
#' @return Calendar year for all seasons except Summer. Summer has financial
#' year ending returned.
#' @export
#'
#' @examples
#' require(lubridate)
#' x <- dmy("1/12/2015") + months(0:12)
#' year(x)
#' # 2015 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016
#' season_year(x)
#' # 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2017
#' season_year(x, shoulder = TRUE)
#' # 2016 2016 2016 2016 2016 2016 2016 2016 2016 2016 2017 2017 2017
season_year <- function(x, shoulder = FALSE) {
UseMethod("season_year")
}
#' @export
season_year.default <- function(x, shoulder = FALSE) {
tibble::data_frame(x = x) %>%
dplyr::mutate(Season = season(x, shoulder = shoulder)) %>%
dplyr::mutate(Year = ifelse(Season == "Summer",
fye(x),
lubridate::year(x))) %>%
.$Year
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.