R/timer.R

Defines functions elapsed_months str_num_month

Documented in elapsed_months str_num_month

#' Get elapsed months between two dates.
#'
#' @param start_date Start date.
#' @param end_date End date
#' @param method Calculation method:\cr
#' \code{round}: Roundes value according to the number of days elapsed.\cr
#' \code{max}: Only one day in the month is enough to count it.\cr
#' \code{min}: Number of elapsed months using \code{lubridate::period}
#'
#' @return A numeric value.
#'
#' @examples
#' # All days in a year
#' timer::elapsed_months(lubridate::dmy("01/01/2000"), lubridate::dmy("31/12/2000"))
#'
#' # All days in a year + 1
#' timer::elapsed_months(lubridate::dmy("01/01/2000"), lubridate::dmy("01/01/2001"))
#'
#' # All days in a year + 1 with max method
#' timer::elapsed_months(lubridate::dmy("01/01/2000"), lubridate::dmy("01/01/2001"), method = "max")
#'
#' @export
elapsed_months <- function(start_date, end_date, method = "round") {

  if (method == "max") {
    elapsed_months <- 12 * (lubridate::year(end_date) - lubridate::year(start_date)) + (lubridate::month(end_date) - lubridate::month(start_date)) + 1

  } else if (method == "round") {
    jour_ecoules <- end_date - start_date
    jour_ecoules <- lubridate::days(jour_ecoules)
    elapsed_months <- jour_ecoules$day / 30
    elapsed_months <- round(elapsed_months)

  } else if (method == "min") {
    elapsed_months <- lubridate::interval(start_date, end_date) %>%
      lubridate::as.period() %>%
      .@month

  }

  return(elapsed_months)
}

#' Get month number from its name.
#'
#' @param str_month A character month vector.
#'
#' @return A vector of numeric months.
#'
#' @examples
#' timer::str_num_month(c("janvier", "FĂ©vrier", "avril"))
#'
#' @export
str_num_month <- function(str_month) {

  months <- dplyr::tibble(month = lubridate::as_date(0:364) %>% months() %>% unique(),
                          num_month = 1:12)

  str_num_month <- dplyr::tibble(month = str_month) %>%
  dplyr::mutate(month = tolower(.data$month)) %>%
  dplyr::left_join(months, by = "month") %>%
  dplyr::pull(.data$num_month)

  return(str_num_month)
}
stephLH/timer documentation built on Dec. 27, 2019, 2:15 p.m.