Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created January 7, 2017 01:02
Show Gist options
  • Save ateucher/87b3f9ac39e1b25924c8c1b6abed8f3a to your computer and use it in GitHub Desktop.
Save ateucher/87b3f9ac39e1b25924c8c1b6abed8f3a to your computer and use it in GitHub Desktop.
Create (and optionally recenter) day of year from date
#' Convert a date to a day of year, optionally setting an arbitrary date as the
#' first day in a year.
#'
#' @param date a vector of dates in a standard unambigous format ("YYYY/MM/DD")
#' @param start_doy the first day of the year ("mm/dd"). Default January 1 ("01/01"), but can be set
#' to any month/day to set an arbitrary start date from which to calculate day of year
#'
#' @return integer vector with values from 1:365 (or 366 if a leap year)
#' @export
#'
#' @examples
#' dates <- c("1965/02/05", "1981/01/01", "2017/12/31")
#' doy(dates)
#' doy(dates, start_doy = "10/01")
doy <- function(date, start_doy = "01/01") {
if (!require(lubridate)) stop("package lubridate required but not available")
date <- as.Date(date)
doy <- yday(date)
if (start_doy != "01/01") {
year <- year(date)
doy <- recenter_doy(year, doy, start_doy)
}
doy
}
#' Convert a day of year based on a calendar year to a day of year using a
#' different start date than January 1.
#'
#' @param year four-digit year
#' @param doy integer day of year
#' @param start_doy the first day of the year ("mm/dd"). Can be set
#' to any month/day to set an arbitrary start date from which to calculate day of year
#'
#' @return integer vector with values from 1:365 (or 366 if a leap year)
#' @export
#'
#' @examples
#' data <- data.frame(year = c(1996, 1997, 1998),
#' doy = c(56, 72, 275))
#' recenter_doy(data$year, data$doy, "10/01")
recenter_doy <- function(year, doy, start_doy) {
if (!require(lubridate)) stop("package lubridate required but not available")
days_in_year <- yday(ymd(paste0(year, "12/31")))
start_doy <- yday(ymd(paste0(year, start_doy)))
ifelse(doy > start_doy,
doy - start_doy,
days_in_year - start_doy + doy)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment