R/month_start_end.R

Defines functions month_start_end

Documented in month_start_end

#' month_start_end
#'
#' Get a start or end date for any month
#' @param year The year
#' @param month The month - can be either a number or the full month name or partial, i.e. 'Sep' or 'Aug'
#' @param start TRUE or FALSE for if you want the start of the month (FALSE would give you the end)
#' @export

month_start_end <- function(year,month,start) {

require(lubridate)
require(tidyverse)

 days_30 <- c('Apr','Jun','Sep','Nov')

  tbl <- tibble(month_name = c('January','February','March','April','May','June','July','August','September','October','November','December'),
                month_code = str_sub(month_name,end=3),
                month_val = 1:12,
                start_date = '01',
                end_date = ifelse(month_code %in% days_30,30,
                      ifelse(month_code == 'Feb',28,31))
                    )

  if (is_leapyear(year)==TRUE) {
    tbl <- tbl %>%
      mutate(end_date = ifelse(month_code == 'Feb',29,end_date))
  }

  if (is.numeric(month)==TRUE) {

    filt_tbl <- tbl %>% filter(month_val == month)
  } else {
    filt_tbl <- tbl %>% filter(month_name == month | month_code == month)
  }

  filt_tbl <- filt_tbl %>% mutate(month_val = ifelse(month_val < 10,paste('0',as.character(month_val),sep=''),as.character(month_val)))

  day_val <- ymd(paste(year,'-',filt_tbl$month_val,'-',ifelse(start==TRUE,filt_tbl$start_date,filt_tbl$end_date),sep=''))

  return(day_val)

}
neugelb/neugelbtools documentation built on July 7, 2020, 1:17 a.m.