I'm working with hydrologic data, and I need water years. I've successfully created a water year column based on a function previously posted on this forum. What I would like is to have an accompanying water day
ranging from 1-365 (366 in leap years) to match the water year sequence. Note the water year is designated by the calendar year in which it ends. For example, the 2010 water year started on October 1, 2009 and ended on September 30, 2010.
Basically I want a column that starts a sequence from 1-365 (366 in leap years) whenever the date hits the first of October in each year.
My dataset ranges from 1950 to 2099, so I need someway to automate this process. The leap year component of this problem is giving me trouble.
I have provided code below to create the dataset.
# Create a data_set with datetime, year, month, day, jd, wtr_yr
library(lubridate)
datetime <- seq(as.Date("1950/1/1"), as.Date("2099/12/31"), by = "day")
year <- year(datetime)
month <- month(datetime)
day <- day(datetime)
julian_day <- yday(datetime)
# make dataframe with all time components
datetime_dataframe <- data.frame(datetime, year, month, day, julian_day)
# Create function to derive water year. Credit goes to Caner and MrFlick.
wtr_yr <- function(dates, start_month=10) {
# 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
}
# Use fn to add water year to the dataframe
datetime_dataframe$wtr_yr <-wtr_yr(datetime_dataframe$datetime)
head(datetime_dataframe)