Skip to content

Instantly share code, notes, and snippets.

@wpetry
Created February 22, 2018 04:15
Show Gist options
  • Save wpetry/db99425e7a092b16df1f107377856c04 to your computer and use it in GitHub Desktop.
Save wpetry/db99425e7a092b16df1f107377856c04 to your computer and use it in GitHub Desktop.
Takes a date and calculates: the water year, the week of the water year, the day of the water year
library(lubridate)
wtr_yr <- function(dates, start_month = 9) {
# Convert dates into POSIXlt
dates.posix <- as.POSIXlt(dates)
# Year offset
offset <- ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year <- dates.posix$year + 1900 + offset
# Return the water year
adj.year
}
wtr_week <- function(dates, start_month = 9) {
offset <- ifelse(month(dates) >= start_month, 0, 1)
(dates - dmy(paste(01,start_month,year(dates)-offset)))[[1]]%/%7 + 1
}
wtr_doy <- function(dates, start_month = 9) {
offset <- ifelse(month(dates) >= start_month, 0, 1)
(dates - dmy(paste(01,start_month,year(dates)-offset)))[[1]] + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment