R/utils.R

Defines functions format_date format_date_mon format_date_to_date add_h1_title add_files_template_tibble check_args new_journalr_tbl_df

format_date <- function(date_vec) format(date_vec, "%a %d %b %Y")
format_date_mon <- function(date_vec) format(date_vec, "%B %Y")
format_date_to_date <- function(date1, date2, f) paste(f(date1), "to", f(date2))

add_h1_title <- function(content, title) {
  paste0("# ", title, "\n\n", content)
}

add_files_template_tibble <- function(df_in, period_type, filename_body){
  df_in %>%
    dplyr::mutate(
      filename = paste0(
        switch(period_type,
               "week" = paste0("~w", .data$id_str),
               "month" = format(.data$start_date, "%Y-%m")),
        "-", filename_body
      ),
    )
}

check_args <- function(date_start, period_type, date_end) {
  # Select dates
  if (!lubridate::is.Date(date_start) | !rlang::is_scalar_double(date_start))
    stop("Start date must be a scalar date object")

  if (!lubridate::is.Date(date_end) | !rlang::is_scalar_double(date_end))
    stop("End date must be a scalar date object")

  if (date_end <= date_start)
    stop("The end date must be after the start date")

  # Ensure week or month periods
  if (!period_type %in% c("week", "month"))
    stop("The indicator 'ind_weeks' must be a scalar logical")

  # If the period is weekly, make sure the start day is a Sunday or Monday
  if (period_type == "week") {
    weekday_start <- weekdays(date_start, FALSE)
    if (weekday_start != "Sunday" & weekday_start != "Monday")
      stop(glue::glue("Start date is a {weekday_start}, not a Sunday or Monday.\n"))
  }

  # If the period is monthly, make sure the start day is the 1st.
  if (period_type == "month" & lubridate::day(date_start) != 1)
    stop("Start date is not the first day of the month.")

  invisible(NULL)
}

new_journalr_tbl_df <- function(date_start, period_type, date_end){

  check_args(date_start, period_type, date_end)

  start_date <- seq.Date(date_start, by = period_type, to = date_end)
  end_date <- lubridate::ceiling_date(start_date, period_type,
                                      week_start = lubridate::wday(date_start - 1)) - 1
  n_periods <- length(start_date)

  # Check compatibility of end date
  if (!any(date_end == end_date))
    stop("Specified end date is not compatible with start date and period type.")

  tibble::tibble(
    start_date = start_date,
    end_date = end_date,
    date_vec = purrr::map2(start_date, end_date, ~format_date(seq(.x, .y, 1))),
    id_str = stringr::str_pad(seq_len(n_periods), width = stringr::str_length(n_periods),
                              side = "left", pad = 0),
    titlename = switch(
      period_type,
      "week" = paste0("Week ", .data$id_str, ": ", format_date_to_date(start_date, end_date, format_date)),
      "month" = format(start_date, "%B %Y")
    )
  )
}
andrewjpfeiffer/journalr documentation built on Oct. 13, 2019, 9:19 p.m.