R/dates.R

Defines functions is_date date_subtraction date_standard_cols

Documented in date_standard_cols date_subtraction is_date

#' Add helpful date columns.
#'
#' @param .df a data frame.
#' @param .date_col the name of the date column unqouted.
#' @return an updated version of the data frame supplied to
#'  .df with four additional date related columns:
#'   1) datetime, 2) date, 3) year, and 4) month.
#' @export

date_standard_cols <- function(.df, .date_col) {
  .date_col <- rlang::enquo(.date_col)

  .df %>%
    dplyr::mutate(datetime = lubridate::as_datetime(!!.date_col, tz = "America/New_York"),
                  date = lubridate::as_date(!!.date_col, tz = "America/New_York"),
                  year = lubridate::year(date),
                  month = lubridate::month(date, label = TRUE, abbr = FALSE))
}




#' Subtract from a provided date.
#'
#' @param .date a vector of dates
#' @param .subtract a string indicating the number of years to subtract
#' from \code{.date}.
#' @return a vector of dates.
#' @example
#' date_subtraction(.date = Sys.Date(), .subtract = "10 years")
#' date.vec <- as.Date(c("2020-01-01", "2020-01-02"))
#' date_subtraction(.date = date.vec, .subtract = "10 years")
#'
#' @export

date_subtraction <- function(.date, .subtract) {
  final.list <- lapply(X = .date, FUN = function(date.i) {
    seq(date.i, length = 2, by = paste0("-", .subtract))[2]
  })
  final.df <- Reduce(f = c,  x = final.list)
  return(final.df)
}

#' Identify if a vector is class date.
#'
#' @param .date a vector.
#' @return a logical vector.
#' @example
#' is_date(Sys.Date())
#' @export

is_date <- function(.date) {
  inherits(.date, "Date")
}
BWAM/stayCALM documentation built on May 21, 2020, 3:24 p.m.