Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Useful helper functions? #283

Open
omuelle opened this issue Apr 5, 2019 · 0 comments
Open

Useful helper functions? #283

omuelle opened this issue Apr 5, 2019 · 0 comments

Comments

@omuelle
Copy link

omuelle commented Apr 5, 2019

I have a few helper functions in the kofbts and kofbarometer package I use on a regular basis. I'm trying to find a place for them. Would they fit in tstools?

#' Returns Date object given year and month. The day is set to 1.
ymDate <- function(year, month)
{
  as.Date(paste0(year, "-", month, "-1"))
}

dateToTime <- function(date)
{
  data.table::year(date) + (data.table::month(date) - 1)/12
}

timeToDate <- function(time)
{
  time <- round(time, 3)
  ymDate(floor(time), round((time - floor(time)) / (1/12)) + 1)
}

startTime <- function(ts)
{
  time(ts)[1]
}

endTime <- function(ts)
{
  time(ts)[length(ts)]
}

startDate <- function(ts)
{
  timeToDate(startTime(ts))
}

endDate <- function(ts)
{
  timeToDate(endTime(ts))
}

frequencyDate <- function(date, frequency)
{
  ymDate(year(date), (ceiling(month(date) / (12/frequency)) - 1) * (12/frequency) + 1)
}

toMonthlySeries <- function(x, fill_last_quarter = F)
{
  vals <- unlist(lapply(as.vector(x), function(val) c(val, NA, NA)))
  if(!fill_last_quarter) {
    vals <- vals[1:(length(vals)-2)]
  }
  ts(vals, start = startTime(x), frequency = 12)
}

#' Add a number of months to a given date. Return NA if the resulting Date does not exist,
#' for example if the day is the 31th and the new month doesn't have 31 days. "months" can
#' be negative.
#' 
#' @param date   Date or character representing a Date.
#' @param months integer, number of months to add, can be negative.
#' @return       Date with months added to date
#' @export
addMonths <- function(date, months) 
{
  m <- data.table::month(date)-1+months
  add_this <- m%%12+1
  
  d_str <- paste0(data.table::year(date)+m%/%12, "-",
                  ifelse(nchar(add_this) == 1, paste0("0", add_this), add_this), "-",
                  data.table::mday(date))
  
  tryCatch({as.Date(d_str)}, error = function(e) NA)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant